对小数进行四舍五入时会得到不同的结果
double radius = 5;
double area = Math.PI * Math.pow(radius, 2);
// System.out.println(area);
BigDecimal bd = new BigDecimal(area).setScale(2, HALF_UP);
// BigDecimal bd = new BigDecimal(area).setScale(2, ROUND_HALF_UP);
System.out.println(bd.toString());
上面的输出打印为 78.54,但如果我通过计算器(Windows calc 接口)执行相同的操作,输出结果为 78.57(即 22/7 * 25
)。
为什么会出现不一致的情况
double radius = 5;
double area = Math.PI * Math.pow(radius, 2);
// System.out.println(area);
BigDecimal bd = new BigDecimal(area).setScale(2, HALF_UP);
// BigDecimal bd = new BigDecimal(area).setScale(2, ROUND_HALF_UP);
System.out.println(bd.toString());
The above output gets printed as 78.54, but if I perform the same operation via the calculator (windows calc interface) the output comes out as 78.57 (i.e. 22/7 * 25
).
Why is there an inconsistency
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否使用
22/7
作为 PI 的近似值?因为22/7
为3.142857142857...
,其中 PI 约为3.14159...
。这解释了您的舍入不一致的情况。JVM 中使用的 PI 近似值记录在 这里。根据JavaDoc,它是:
Are you using
22/7
as an approximate value for PI? Because22/7
is3.142857142857...
where PI is approximately3.14159...
. This explains your rounding inconsistencies.The approximation of PI that is used in the JVM is documented here. According to the JavaDoc, it is:
22/7
是PI
的近似值,它不准确,所以结果22/7
is approximation toPI
, Its not exact and so the result几乎完全偏离主题(及其 javascript)。但这仍然是一个有趣的答案,因为可以实际看到 PI 的计算结果。
这种方法在计算 PI 时显然超级超级慢……但是看起来很有趣。
Philippe Leybaert 设置了一个JSBin 。
Almost completely off-topic (and its javascript). But its still a fun answer for actually visibly seeing PI being calculated.
This method is obviously super-super-slow at calculating PI...but is kinda fun to watch.
Philippe Leybaert set up a JSBin for it.