1. Home
  2. Computing & Technology
  3. Ruby

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

By , About.com Guide

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
More Ruby Q&A
Explore Ruby
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Ruby
  4. Tasks & Scripts
  5. FAQs
  6. How do I round a float down if it's close to a whole number?

©2009 About.com, a part of The New York Times Company.

All rights reserved.