Math.round / Divide task with great value

I have a problem with dividing a long value by 1000 and rounding to an integer.

My long value: 1313179440000

My code

long modificationtime = 1313179440000; Math.round(modificationtime/1000l) 

If I print the divided and formed value, it returns me: 1313179392

So.

 value : 1313179440000 expected: 1313179440 got : 1313179392 

I do not know why this is happening. Can anybody help me?

Regards, prdatur

+4
source share
2 answers

Math.round(float) . The float has a larger range than the long one, but it cannot represent all integers in this range - in this case, the integer 1313179440 (the original division result) lies in the part of the range that exceeds the integer accuracy.

  • Do not use Math.round as it is not needed (input is already an integer!) Or;

  • Use Math.round(double) , as in: Math.round(modificationTime/1000d) . Note that the divisor is double, and therefore the dividend (and result) of the expression also rises to double.

Happy coding.

+9
source

The reason for this is that Math.Round() accepts either double . Since your number is not exactly represented as a double , the closest number to be transmitted.

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

+3
source

Source: https://habr.com/ru/post/1369223/


All Articles