1

I am simply trying to get milliseconds to display the first two digits of the variable.

What I expect to work (I see two digits initially, then as it is incremented I see three digits):

@Override
public String toString() {
    Long milliSeconds = TimeUnit.MILLISECONDS.toMillis(elapsedTime) % 1000;
    Long seconds = (TimeUnit.MILLISECONDS.toSeconds(elapsedTime));
    return String.format("%2d.%02d seconds", seconds, milliSeconds);
}

What actually works:

@Override
public String toString() {
    String milliSeconds = String.format("%02d",
            TimeUnit.MILLISECONDS.toMillis(elapsedTime) % 1000).substring(0, 2);
    Long seconds = (TimeUnit.MILLISECONDS.toSeconds(elapsedTime));
    return String.format("%2d.%s seconds", seconds, milliSeconds);
}

Or:

@Override
public String toString() {
    double milliSeconds = (double)(TimeUnit.MILLISECONDS.toMillis(elapsedTime) % 1000) / 1000;
    Long seconds = (TimeUnit.MILLISECONDS.toSeconds(elapsedTime));
    return String.format("%.2f seconds", seconds + milliSeconds);
}

I guess my first question would be are either of my solutions that work more resource intensive than the one that doesn't? And secondly, what am I doing wrong in the first solution? I would expect %02d to take the long and truncate it to 2 digits buffered with a 0. Instead I see the two digits plus a trailing 0.

2 Answers 2

2
System.out.printf("%07.3f seconds", (elapsedTime / 1000f));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, elapsedTime was a Long but this works: return String.format("%.2f seconds", (float)elapsedTime / 1000f);
If one of the operands is a floating point and the other is an integer then the result will be a floating point. The literal on the 1000 will define it as a float, there is also d and l for double and long.
2

milliseconds should be %03d not %02d.

If you want the resolution to be at the tens of milliseconds level, then you'll have to do a little "fancy" calculating.

return String.format("%2d.%02d seconds", seconds, milliSeconds / 10);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.