[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

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

Gavin Kistner

10/13/2006 3:48:00 PM

From: Jatinder Singh [mailto:jatinder.saundh@gmail.com]
> 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