Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying how many numbers after a decimal point

 a = '60.950'
 b = a.to_f

 puts a # => 60.950
 puts b # => 60.95

I want to display three digits after the decimal point everytime. How can I force 0 at the end of b?

like image 324
William Li Avatar asked Nov 23 '25 08:11

William Li


2 Answers

Use sprintf.

sprintf('%.3f', 60.95)
# => "60.950"
like image 89
oldergod Avatar answered Nov 25 '25 20:11

oldergod


Use the mother of the formatting methods, such as String#% or printf or sprintf, which is Kernel#format

puts format('%.3f', 0)

The others refer to this, and the Kernel#format documentation has the full documentation tables.

like image 21
vgoff Avatar answered Nov 25 '25 22:11

vgoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!