android java String.format padding zeroes before and after decimal on a double

I’ve made a quick timer and I’m trying to display the time in the format “00:00.00” where the first 00 is the minutes and the 00.00 is the seconds and fraction of seconds. I have the below format code:

// Get the delta time
long timeDelta = System.currentTimeMillis()-startTimeMillis;

int minutes;
double seconds;

// Now split
if( timeDelta>60000 ) { // Minutes
    minutes = (int)(timeDelta/60000);
    timeDelta-= minutes*60000;
    minutes = 0;

// Now for the rest
seconds = timeDelta/1000.0;

// Get the text string
final String timeString = String.format( "%1$02d:%2$02.2f", minutes, seconds );

But the string keeps coming out like “00:6.42” instead of “00:06.42”. How can I get String.format to format the decimal with leading zeroes and the decimal places?


A better way to do that in Java is to use SimpleDateFormatlike this :

long timeDelta = System.currentTimeMillis()-startTimeMillis;

SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("mm:ss:SS");

Working example

Leave a Reply

Your email address will not be published. Required fields are marked *