title | description |
---|---|
Floating-point cheat sheet for Ruby |
Tips for using floating-point and decimal numbers in Ruby |
Ruby floats are mapped to double-precision IEEE 754.
f = 0.1
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
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
Ruby 浮点映射 IEEE 754 双精度浮点.
f = 0.1
在 Ruby 的 bigdecimal
模块中有一个称为 BigDecimal
的 arbitrary-precision 小数类型,它同时允许选择 取整模式。
require 'bigdecimal'
a = BigDecimal('0.1')
b = BigDecimal('0.2')
c = a + b # 返回 BigDecimal 表示的精确的 0.3
得到字符串:
"%.2f" % 1.2399 # 返回 "1.24"
"%.3f" % 1.2399 # 返回 "1.240"
"%.2f" % 1.2 # 返回 "1.20"
打印到标准输出:
puts "%.2f" % 1.2399