java Math.round / 除以长值的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7209510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Math.round / Divide problem with a long value
提问by prdatur
I have a problem with dividing a long value by 1000 and round it to an integer.
我在将 long 值除以 1000 并将其四舍五入为整数时遇到问题。
My long value is: 1313179440000
我的多头值是:1313179440000
My code is
我的代码是
long modificationtime = 1313179440000;
Math.round(modificationtime/1000l)
If i print out the divided and formated value, it returns me: 1313179392
如果我打印出分割和格式化的值,它会返回我:1313179392
so.
所以。
value : 1313179440000
expected: 1313179440
got : 1313179392
I do not know why this happens. Can anybody help me?
我不知道为什么会这样。有谁能够帮我?
best regards, prdatur
最好的问候,prdatur
回答by
Math.round(float)
is being used. A float has a larger rangethan a long, but it cannot represent all integers within that range -- in this case the integer 1313179440 (the original resultof the division) lies in the part of the range that exceeds integer precision.
Math.round(float)
正在使用。float 的范围比 long 大,但它不能表示该范围内的所有整数——在这种情况下,整数 1313179440(除法的原始结果)位于超出整数精度的范围部分。
Don't use
Math.round
as it's not needed (input is already an integer!), or;Use
Math.round(double)
, as in:Math.round(modificationTime/1000d)
. Note that the divisor is a double and thus the dividend (and the result) of the expression are also promoted to double.
不要使用,
Math.round
因为它不需要(输入已经是一个整数!),或者;使用
Math.round(double)
,如:Math.round(modificationTime/1000d)
。请注意,除数是双精度数,因此表达式的被除数(和结果)也被提升为双精度数。
Happy coding.
快乐编码。
回答by dlev
The reason you get that result is that Math.Round()
accepts either a double
. Since your number isn't exactly representable as a double
, the closest number that isgets passed in.
你得到这个结果的原因是Math.Round()
接受一个double
. 由于您的号码是不完全表示为一个double
,即最接近的数字是在被传递。
Note that round()
is completely unnecessary here. modificationTime/1000l
requires no rounding. If you dorequire rounding, change the argument to modificationTime/1000d
.
请注意,round()
这里完全没有必要。modificationTime/1000l
不需要四舍五入。如果确实需要舍入,请将参数更改为modificationTime/1000d
。