Mikey A. Leonetti
Mikey A. Leonetti

Reputation: 3342

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;
}
else
    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?

Upvotes: 0

Views: 329

Answers (1)

Ashish Ranjan
Ashish Ranjan

Reputation: 5543

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");
System.out.println(simpleDateFormat.format(timeDelta));

Working example

Upvotes: 2

Related Questions