Ruby number formatting: only show decimals if there are any

Posted Over 10 years ago. Visible to the public.

Warning: Because of (unclear) rounding issues and missing decimal places (see examples below),
do NOT use this when dealing with money. Use our amount helper instead.


In Ruby, you can easily format strings using % (short for Kernel#sprintf):

'%.2f' % 1.23456 #=> 1.23
'%.2f' % 2 #=> 2.00

However, what if you only want the decimals to be shown if they matter? There is g! It will limit the total number of displayed digits, disregarding the decimal point position. Now use f to round to n decimal places, then tweak the relevant digits using g:

# g limits the number of displayed digits
"%.2g" % 1.234 # => 1.2
"%.2g" % 123 # => 1.2e+02
"%g" % 1000000000 # => 1e+09

# combined
"%g" % ("%.2f" % 2) #=> 2
"%g" % ("%.2f" % 2.50) #=> 2.5
"%g" % ("%.2f" % 12.543) #=> 12.54

# specifying how many digits to display (6 is default)
"%g" % ("%.2f" % 9999.99) #=> 9999.99
"%g" % ("%.2f" % 99999.99) #=> 100000
"%.10g" % ("%.2f" % 99999.99) #=> 99999.99
"%.3g" % ("%.2f" % 13.99) #=> 14
"%.3g" % ("%.2f" % 13.49) #=> 13.5
"%.3g" % ("%.2f" % 13.45) #=> 13.4 woot?!

Also see this thread on SO Show archive.org snapshot .

From the Ruby docs Show archive.org snapshot :

g: Convert a floating point number using exponential form if the exponent is less than -4 or greater than or equal to the precision, or in dd.dddd form otherwise. The precision specifies the number of significant digits.

Dominik Schöler
Last edit
Over 8 years ago
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2014-01-31 17:28)