Android:java舍入错误.无法理解为什么?

任何人都能解释为什么地球上这些“相同”的表达式会返回不同的值吗?
(new BigDecimal(String.valueOf(131.7d))).multiply(new BigDecimal(String.valueOf(0.95d))).doubleValue() = 125.115

(new BigDecimal(               131.7d )).multiply(new BigDecimal(               0.95d )).doubleValue() = 125.11499999999998

BigDecimal在它们之间有什么不同?

解决方法

如果您阅读api文档,您会发现taht String.valueOf(dobule)使用Double.toString(double)来格式化值.它可能并不明显,但Double.toString(double)将值格式化,然后将其格式化为字符串:

How many digits must be printed for the fractional part of m or a?
There must be at least one digit to represent the fractional part,and
beyond that as many,but only as many,more digits as are needed to
uniquely distinguish the argument value from adjacent values of type
double. That is,suppose that x is the exact mathematical value
represented by the decimal representation produced by this method for
a finite nonzero argument d. Then d must be the double value nearest
to x; or if two double values are equally close to x,then d must be
one of them and the least significant bit of the significand of d must
be 0.

结果是String.valueOf(131.7d)将返回字符串“131.7”,即使参数的确切值是131.69999999999998863131622783839702606201171875.原因是十进制分数不能总是使用二进制分数精确表示(与浮点数和双精度数一起使用).

因此,新的BigDecimal(String.valueOf(131.7))将创建一个精确值为131.7的BigDecimal. new BigDecimal(131.7)将创建一个具有精确值131.69999999999998863131622783839702606201171875的BigDecimal.

相关文章

Android 通过adb shell命令查看内存,CPU,启动时间,电量等...
Monkey Android app稳定性测试工具之Monkey使用教程 by:授客...
Android 常见adb命令 by:授客 QQ:1033553122 1、 查看所有已...
这篇“android轻量级无侵入式管理数据库自动升级组件怎么实现...
今天小编给大家分享一下Android实现自定义圆形进度条的常用方...
这篇文章主要讲解了“Android如何解决字符对齐问题”,文中的...