给定以下行
BigDecimal step = 10.0G**-1.0G
groovy 1.7.5 返回错误
0.1000000000000000055511151231257827021181583404541015625
groovy 1.8 返回正确的
0.1
不幸的是,我想在 Grails 中解决我的问题。 1.4 与 groovy 1.8 还不够稳定( Controller 在开发模式下不会刷新),而 grails 1.3.7 与 groovy 1.7.x 一起提供
两个问题:
我做错了什么还是 1.7.5 中的错误?
如何避免这种行为?我认为 BigDecimals 非常适合这种舍入问题?
第二次更新:(忘记第一次更新)-;
我现在有点困惑。似乎我每次尝试都会得到不同的结果......:
BigDecimal step = 10.0G**-1.0G
println step
返回0.1000000000000000055511151231257827021181583404541015625
和
println 10.0G**-1.0G
返回
0.1
在两个 groovy 版本中。
但是,如果您只是将 BigDec step = 10.0G**-1.0G
放入 groovyConsole 并让控制台打印最后的响应,则不同的 groovy 版本会得到不同的结果。所以问题之一似乎是 groovyConsole。
另一个问题似乎是执行的 toString 转换。
似乎涉及到一些自动装箱......当我执行
def step = 10.0G**-1.0G
结果是 double ...
我想这将问题归结为两个问题:
- a) 哪些数学运算是 BigDecimal 运算?
和
- b) 如何轻松舍入 BigDecimal 以便纠正上述问题?
感谢您的耐心等待
最佳答案
我想我已经明白了。这是 java 文档中的线索:
BigDecimal(double val) Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value.
- 因此,我在代码中使用的 Math.-Functions 似乎不支持 BigDecimal。
- 结果在后台从 Double 转换为 BigDecimal
- 当 double 为
0.1
时, double 的二进制精确表示为0.1000000000000000055511151231257827021181583404541015625
println 10.0G**-1.0G
打印 double 值 (0.1
)BigDecimal 步长 = 10.0G**-1.0G; println 步骤
打印 double0.1
的 BigDecimal 表示,这是上面的难看的数字
看起来 groovy 版本的行为(就 BigDecimals 而言)没有差异,但是结果在 groovyConsole 中的输出方式存在差异。
关于Groovy BigDecimal 精度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6327257/