Floating-point cheat sheet for Ruby
Floating-Point Types
Ruby floats are mapped to double-precision IEEE 754.
f = 0.1
Decimal Types
Ruby has an arbitrary-precision decimal type named BigDecimal
in the bigdecimal
module, which also allows to choose the rounding mode.
require 'bigdecimal'
a = BigDecimal('0.1')
b = BigDecimal('0.2')
c = a + b # returns a BigDecimal representing exactly 0.3
How to Round
To get a string:
"%.2f" % 1.2399 # returns "1.24"
"%.3f" % 1.2399 # returns "1.240"
"%.2f" % 1.2 # returns "1.20"
To print to standard output:
puts "%.2f" % 1.2399
Resources
© Published at floating-point-gui.de under the Creative Commons Attribution License (BY)