[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

Tomasz Wegrzanowski

10/13/2006 3:57:00 PM

On 10/13/06, Jatinder Singh <jatinder.saundh@gmail.com> wrote:
> Hi,
>
> 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.
>
> Please share if you know.

One way is sprintf:

sprintf "%.4f", 0.7458745 #=> "0.7459"

Another is multiple, round, divide:

class Float
alias_method :round_orig, :round
def round(n=0)
(self * (10.0 ** n)).round_orig * (10.0 ** (-n))
end
end

0.7458745.round(4) # => 0.7459

That's about what you can get in Ruby. It should suffice for most programs.

Of course no Float-based method can give you correct decimal arithmetic
(with nearest even rounding etc.). You need a special package for that.

0.15.round(1) # => 0.2 correct
0.25.round(1) #=> 0.3 should be 0.2

sprintf "%.1f", 0.15 #=> "0.1" should be 0.2
sprintf "%.1f", 0.25 #=> "0.2" correct

--
Tomasz Wegrzanowski [ http://t-a-w.blo... ]