1

我刚刚将我的 Ruby 版本切换到 1.9.2,而在 Ruby 1.8 中工作的 BigDecimal 代码不再工作了。这是测试代码显示发生了什么

irb(main):001:0> require 'bigdecimal'
=> true
irb(main):002:0> (BigDecimal.new("1")/BigDecimal.new("3")).to_s("F")
=> "0.33333333"
irb(main):003:0> (BigDecimal.new("1", 20)/BigDecimal.new("3", 20)).to_s("F")
=> "0.33333333"

我的 Ruby 安装有问题?否则我认为即使在 Ruby 1.9 中,上面的测试代码仍然可以工作,这是怎么回事?

4

1 回答 1

2

Seems changes in Ruby 1.9 make '/' will not get it significant digits specified from two operand, which works in Ruby 1.8.

Above code wouldn't work because two operand for '/' will only have on significant digitals, and make it float num, and float num will always generate float result by using '/' method.

Instead, in that situation, I should use div(value, digits)

(BigDecimal.new("1", 20).div(BigDecimal.new("3", 20), 50)).to_s("F")
=> "0.33333333333333333333333333333333333333333333333333"

Hope that make sense.

于 2010-09-28T08:44:56.010 回答