Jens Bodal
Jens Bodal

Reputation: 1757

Java: Why isn't String.format() working on this Long variable?

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.

Upvotes: 1

Views: 485

Answers (2)

mrres1
mrres1

Reputation: 1155

System.out.printf("%07.3f seconds", (elapsedTime / 1000f));

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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);

Upvotes: 2

Related Questions