Math.round / 具有长值的除法问题
我在将长值除以 1000 并将其四舍五入为整数时遇到问题。
我的长值是: 1313179440000
我的代码是
long modificationtime = 1313179440000;
Math.round(modificationtime/1000l)
如果我打印出划分和格式化的值,它会返回我: 1313179392
如此。
value : 1313179440000
expected: 1313179440
got : 1313179392
我不知道为什么会发生这种情况。 有人可以帮助我吗?
此致, 普达图尔
I have a problem with dividing a long value by 1000 and round it to an integer.
My long value is: 1313179440000
My code is
long modificationtime = 1313179440000;
Math.round(modificationtime/1000l)
If i print out the divided and formated value, it returns me:
1313179392
so.
value : 1313179440000
expected: 1313179440
got : 1313179392
I do not know why this happens.
Can anybody help me?
best regards,
prdatur
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正在使用Math.round(float)。 float 的范围比 long 更大,但它不能表示该范围内的所有整数 - 在本例中,整数 1313179440(除法的原始结果)位于在超出整数精度的范围部分。
不要使用
Math.round
,因为不需要(输入已经是整数!),或者;使用
Math.round(double)
,如:Math.round(modificationTime/1000d)
。请注意,除数是双精度型,因此表达式的被除数(和结果)也会提升为双精度型。快乐编码。
Math.round(float)
is being used. A float has a larger range than a long, but it cannot represent all integers within that range -- in this case the integer 1313179440 (the original result of the division) lies in the part of the range that exceeds integer precision.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.Happy coding.
得到该结果的原因是
Math.Round()
接受double
。由于您的数字不能完全表示为double
,因此会传入最接近的数字。请注意,
round()
是完全不必要的这里。modificationTime/1000l
不需要舍入。如果您确实需要舍入,请将参数更改为modificationTime/1000d
。The reason you get that result is that
Math.Round()
accepts either adouble
. Since your number isn't exactly representable as adouble
, the closest number that is gets passed in.Note that
round()
is completely unnecessary here.modificationTime/1000l
requires no rounding. If you do require rounding, change the argument tomodificationTime/1000d
.