Force Ruby to not output a float in standard form / scientific notation / exponential notation

f.printf "My number: %.5f\n", small_number

You can replace .5 (5 digits to the right of the decimal) with any particular formatting size you like, e.g., %8.3f would be total of 8 digits with three to the right of the decimal, much like C/C++ printf formatting strings.


If you always want 5 decimal places, you could use:

"%.5f" % small_number

I would do something like this so you can strip off trailing zero's:

puts ("%.15f" % small_number).sub(/0*$/,"")

Don't go too far past 15, or you will suffer from the imprecision of floating point numbers.

puts ("%.25f" % 0.01).sub(/0*$/,"")
0.0100000000000000002081668

Tags:

Ruby