Skip to content

Instantly share code, notes, and snippets.

@c80609a
Created January 2, 2021 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c80609a/747302a1485a43aeeb9f1d87994dca71 to your computer and use it in GitHub Desktop.
Save c80609a/747302a1485a43aeeb9f1d87994dca71 to your computer and use it in GitHub Desktop.
Ruby number formatting
# 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?!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment