Created
January 2, 2021 11:23
-
-
Save c80609a/747302a1485a43aeeb9f1d87994dca71 to your computer and use it in GitHub Desktop.
Ruby number formatting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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