Question

Here is the extracted code :

long timeMs = 1473;
double timeS = (timeMs / 1000) + (timeMs% 1000) / 1000.0;
System.out.println(timeS);

And the output is:

1.4729999999999999

So basically, I was just trying to convert the time taken in seconds into milliseconds. After I saw this I thought my method is wrong, so I've tried other inputs, such as 1472, 1474, 1173, 3 etc which all gave the correct values(1.472, 1.474, 1.173, 0.003).

I think I've came across something similar to this a while ago in a book called Java Puzzlers, but have forgotten. Can anyone tell me why this is happening (and a proper term/error)?

Thanks.

Était-ce utile?

La solution

Use this instead, but it's because of IEEE 754 rounding rules.

double timeS = (timeMs / 1000.0); //+ ((double) (timeMs % 1000) / 1000.0);

Autres conseils

Use BigDecimal for more accurate rounding and scaling.

   long timeMs = 1473;
   double timeS = (timeMs / 1000d);
   BigDecimal usefulName = new BigDecimal(timeS).setScale(3, RoundingMode.HALF_UP);
   System.out.println(usefulName);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top