Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format a float to a certain number of decimal and integer digits?

Tags:

ruby

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?

like image 738
Raven Dreamer Avatar asked Jul 03 '13 02:07

Raven Dreamer


1 Answers

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" 
like image 94
oldergod Avatar answered Oct 07 '22 18:10

oldergod