1. Computing
Send to a Friend via Email

How do I round a float down if it's close to a whole number?

By

Question: How do I round a float down if it's close to a whole number?
Answer:

There is no built in method to do this. However, using Ruby's open classes, you can add this to the Float class.

There's a simple, one-liner way to do this. The Float#floor method will return the largest integer equal to or less than the floating point value. In other words, the integer portion of the number. Subtract this from the number the floating point number to get the fractional portion. If the fractional portion is 0, return just the integer.

 #!/usr/bin/env ruby
 
 class Float
   def to_i_if
     if self - floor == 0
       floor
     else
       self
     end
   end
 end
 

You may also want to add a threshold parameter. Floating point numbers are not always that accurate, so the fractional portion may not equal exactly zero. This will handle situations like 3.000002, where the fractional portion is so insignificant it can be ignored.

 #!/usr/bin/env ruby
 
 class Float
   def to_i_if(threshold=0)
     if self - floor <= threshold
       floor
     else
       self
     end
   end
 end
 
The following is an example IRB session demonstrating the usage.
 irb(main):001:0> load 'float_round.rb'
 => true
 irb(main):002:0> 1.0.to_i_if
 => 1
 irb(main):003:0> 1.0001.to_i_if
 => 1.0001
 irb(main):004:0> 1.0001.to_i_if(0.001)
 => 1
 

©2014 About.com. All rights reserved.