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
end
end

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

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

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