# How do I round off a float to x decimal places

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.

Regards,
Jatinder

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.

It rather depends on which of the 14-or-so regulalrly used rounding
algorithms you need.

Float#round has an inbuilt bias toward zero and is therefore not a
useful unbiased rounding in many circumstances.

Martin

Martin C. wrote:

Float#round has an inbuilt bias toward zero and is therefore not a
useful unbiased rounding in many circumstances.

Martin

Chekc out:

http://facets.rubyforge.org/api/core/index.html

Look for the round_* methods.

T.

Thanks you all for the solutions!

Regards,
Jatinder

On 10/13/06, Martin C. [email protected] wrote:

Float#round has an inbuilt bias toward zero and is therefore not a
useful unbiased rounding in many circumstances.

But, to answer your original question: if you want a number to three
decimal places:

Multiply by 10^n
Round()
Divide by 10^n

Martin

On 10/13/06, Jatinder S. [email protected] 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.

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

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