简体   繁体   English

四舍五入负浮动文字-Java

[英]rounding up negative floating literal - java

Why does -0.5 when being passed on the Math.round results to 0? 为什么将-0.5传递给Math.round时结果为0? and 0.5 when being passed also results to 1? 和0.5时通过还导致1? shouldn't it be that when you pass -0.5 to Math.round() should also produce -1 as result? 难道不是当您将-0.5传递给Math.round()时也会产生-1的结果吗? I obtained the -1 result when the number was -0.6. 当数字为-0.6时,我得到-1的结果。

Math.round(double) is documented as: Math.round(double)记录为:

Returns the closest long to the argument, with ties rounding to positive infinity. 返回最接近参数的long,并舍入为正无穷大。

So -0.5 is rounding up (towards positive infinite) instead of down towards negative infinity. 因此-0.5是向上舍入(朝正无穷大),而不是向下舍入到负无穷大。 It's behaving exactly as documented. 它的行为与所记录的完全相同。

The working of round( x ) is implemented as floor( x + 0.5 ) until Java6 atleast. 在Java6至少发布之前,round(x)的工作被实现为floor(x + 0.5)。 So, by that logic, floor(-0.5 + 0.5) gives you 0 and floor(0.5+0.5) gives you 1 因此,按照这种逻辑,floor(-0.5 + 0.5)给您0,floor(0.5 + 0.5)给您1

You can refer this link for more details 您可以参考此链接以获取更多详细信息

Why does Math.round(0.49999999999999994) return 1 为什么Math.round(0.49999999999999994)返回1

If you read the docs , it says that round() "returns the closest long to the argument, with ties rounding up." 如果您阅读文档 ,则说明round() “返回最接近参数的long,并且舍入为整数。”

"Up" is towards positive infinity, not away from 0. “向上”朝向正无穷大,而不是远离0。

ETA : I see from Jon Skeet's answer that Java 8 docs improved the clarity on this. ETA :从Jon Skeet的回答中可以看出,Java 8文档改善了这一点。 This answer quotes Java 7, which is bit more confusing than what 8 says. 这个答案引用了Java 7,它比8说的更混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM