Java 故障?减去数字?
这是Java中的一个错误吗?
我去解这个表达式:3.1 - 7.1
我得到答案:-3.9999999999999996
这是怎么回事?
Is this a glitch in Java?
I go to solve this expression: 3.1 - 7.1
I get the answer: -3.9999999999999996
What is going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
可以在这里找到很好的解释。 http://www.ibm.com/developerworks/java/library/j -jtp0114/
请参阅提供的参考以获取更多信息。
A great explanation can be found here. http://www.ibm.com/developerworks/java/library/j-jtp0114/
See the provided reference for more information.
正如其他几个人所提到的,如果您想获得精确的十进制值(例如在实现货币应用程序时),则不能指望
double
。相反,您应该做的是仔细查看 BigDecimal :As mentioned by several others you cannot count on
double
if you would like to get an exact decimal value, e.g. when implementing monetary applications. What you should do instead is to take a closer look at BigDecimal:计算机是 100% 的,所以在数学世界中这是正确的,但对普通人来说则不然。 Java 不能在特定数字上出现错误,因为它只是以相同方式运行但具有不同输入的代码!
PS Google 如何对数字进行四舍五入
Computers are 100% so in the math world that is correct, to the average person it is not. Java cant have a error on a specific number as it is just code that runs the same way but has a different input!
P.S. Google how to round a number
浮点数的舍入误差
与
3 * 0.1 != 0.3
相同(至少当编译器没有折叠时)rounding errors in floating points
same way that
3 * 0.1 != 0.3
(when it's not folded by the compiler at least)自动类型升级正在发生,这就是结果。
这里有一些学习资源。
http://docs.oracle.com/javase/specs /jls/se5.0/html/conversions.html
下一步是学习使用格式化程序将其格式化为给定的精度/要求。
Automatic type promotion is happening and that is the result.
Here is some resource to learn.
http://docs.oracle.com/javase/specs/jls/se5.0/html/conversions.html
The next step would be is to learn to use formatters to format it to the given precision / requirements.