Re: How do I round off a float to x decimal places

From: Jatinder S. [mailto:[email protected]]

This might be a very naive question but I looked through ruby:Float
documentation for a method which round off’s a float number
to x decimal
places with no luck.

To get the result as a number (which, due to floating point precision,
might not be an exact representation of what you wanted):
class Numeric
def round_to( decimals )
factor = 10 ** decimals
( self * factor ).round * 1.0 / factor

(Bonus - works with “negative” decimals, to round to tens or hundreds or

To get the result as a string, which is probably what you really wanted:
class Numeric
def round_to_string( decimals )
“%.#{decimals}f” % self

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs