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
?
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.
Floats have a static, fixed precision. You can't change it. What you can sometimes do, is round the number.
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.
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) ).
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.
You can use sprintf:
sprintf("%0.02f", 123.4564564)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With