开发者

Math.round / Divide problem with a long value

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 w开发者_如何转开发hy this happens. Can anybody help me?

best regards, prdatur


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.

  1. Don't use Math.round as it's not needed (input is already an integer!), or;

  2. 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.


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 is gets passed in.

Note that round() is completely unnecessary here. modificationTime/1000l requires no rounding. If you do require rounding, change the argument to modificationTime/1000d.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜