Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the display precision of a float in Ruby

Is it possible to set the display precision of a float in Ruby?

Something like:

z = 1/3 z.to_s    #=> 0.33333333333333 z.to_s(3) #=> 0.333 z.to_s(5) #=> 0.33333 

Or do I have to override the to_s method of Float?

like image 228
salt.racer Avatar asked Dec 19 '09 19:12

salt.racer


People also ask

How do you set precision in Ruby?

Example: # Ensure we store z as a float by making one of the numbers a float. z = 1/3.0 # Format the float to a precision of three. format('%<num>0.3f', num: z) # => "0.333" format('%<num>0.5f', num: z) # => "0.33333" # Add some text to the formatted string format('I have $%<num>0.2f in my bank account.

How do you change the precision of a float?

Floats have a static, fixed precision. You can't change it. What you can sometimes do, is round the number.

How do you round a float to 2 decimal places in Ruby?

Ruby has a built in function round() which allows us to both change floats to integers, and round floats to decimal places. round() with no argument will round to 0 decimals, which will return an integer type number. Using round(1) will round to one decimal, and round(2) will round to two decimals.

How do I limit decimal places in Ruby?

The round() method can be used to round a number to a specified number of decimal places in Ruby. We can use it without a parameter ( round() ) or with a parameter ( round(n) ).


2 Answers

z.round(2) or x.round(3) is the simplest solution. See http://www.ruby-doc.org/core-1.9.3/Float.html#method-i-round.

That said, that will only ensure that it is no more than that many digits. In the case of 1/3 that is fine, but if you had say 0.25.round(3) you will get 0.25, not 0.250.

like image 78
DrewB Avatar answered Sep 19 '22 03:09

DrewB


You can use sprintf:

sprintf("%0.02f", 123.4564564) 
like image 42
Thomas Bonini Avatar answered Sep 20 '22 03:09

Thomas Bonini