'How can I format a float to a certain number of decimal and integer digits?
I am trying to format a float in Ruby to exactly four digits, including the decimal.
For instance:
1 => 01.00
2.4 => 02.40
1.4455 => 01.45
Right now, I am trying to format the float as follows:
str_result = " %.2f " %result
Which successfully limits the decimal places to two.
I'm also aware of:
str_result = " %2d " %result
Which succesfully turns 1
into 01
, but loses the decimal places.
I tried to combine these like so:
str_result = " %2.2f " %result
to no apparent effect. It has the same results as %.2f
.
Is there a way to force Ruby to format the string into this four digit format?
Solution 1:[1]
You can use sprintf('%05.2f', value)
.
The key is that the format is width . precision
, where width
indicates a minimum width for the entire number, not just the integer portion.
def print_float(value)
sprintf('%05.2f', value)
end
print_float(1)
# => "01.00"
print_float(2.4)
# => "02.40"
print_float(1.4455)
# => "01.45"
Solution 2:[2]
If you are using Rails, you can also use the number_with_precision helper. Example:
<%= number_with_precision(my_float, precision: 2) %>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | the Tin Man |
Solution 2 | Motine |