1
long startTime = System.currentTimeMillis();
float resultTime= (System.currentTimeMillis() - startTime) / 1000;
System.out.println("Result time : " + resultTime);

The result is always a rounded value like 1.0 or 2.0. How can I obtain an exact result like 1.234?

TGM
  • 1,659
  • 10
  • 30
  • 45
  • possible duplicate of [Java float division precision](http://stackoverflow.com/questions/7286681/java-float-division-precision) – Brian Roach Dec 26 '11 at 23:04

2 Answers2

4

You're doing integer division. (which rounds down to an integer)

Cast to float before you do the division:

float resultTime= (float)(System.currentTimeMillis() - startTime) / 1000.0f;
Mysticial
  • 464,885
  • 45
  • 335
  • 332
2

Instead of dividing by 1000, divide by 1000.0. That way instead of doing integer division, you do floating point division.

Dan
  • 10,531
  • 2
  • 36
  • 55