8

I have the same problem as is found here for python, but for ruby.

I need to output a small number like this: 0.00001, not 1e-5.

For more information about my particular problem, I am outputting to a file using f.write("My number: " + small_number.to_s + "\n")

For my problem, accuracy isn't that big of an issue, so just doing an if statement to check if small_number < 1e-5 and then printing 0 is okay, it just doesn't seem as elegant as it should be.

So what is the more general way to do this?

Community
  • 1
  • 1
wrhall
  • 1,288
  • 1
  • 12
  • 26

4 Answers4

10
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.

pjs
  • 18,696
  • 4
  • 27
  • 56
9

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

"%.5f" % small_number
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
3

This works also on integers, trim excess zeros, and always returns numbers as a valid floating point number. For clarity, this uses the sprintf instead of the more cryptic % operator.

def format_float(number)
  sprintf('%.15f', number).sub(/0+$/, '').sub(/\.$/, '.0')
end

Examples:

format_float(1) => "1.0"
format_float(0.00000001) => "0.00000001"
Shai Coleman
  • 868
  • 15
  • 17
2

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
Shawn Balestracci
  • 7,380
  • 1
  • 34
  • 52