简体   繁体   中英

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.

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);
System.out.printf("%07.3f seconds", (elapsedTime / 1000f));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM