Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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?

like image 684
wrhall Avatar asked May 06 '13 17:05

wrhall


4 Answers

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.

like image 108
pjs Avatar answered Nov 17 '22 09:11

pjs


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

"%.5f" % small_number
like image 32
Dan Tao Avatar answered Nov 17 '22 09:11

Dan Tao


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
like image 2
Shawn Balestracci Avatar answered Nov 17 '22 09:11

Shawn Balestracci


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"
like image 2
Shai Coleman Avatar answered Nov 17 '22 09:11

Shai Coleman