Skip to content Skip to sidebar Skip to footer

How To Format Longs In Android To Always Display Two Digits

I have a countdown timer which shows seconds from 60 to 0 (1 min countdown timer). When it reaches 1 digit numbers such as 9,8,7.. it shows 9 instead of 09. I tried using String.fo

Solution 1:

You can accomplish it with DecimalFormat:

NumberFormatf=newDecimalFormat("00");
longtime=9;
textView.setText(f.format(time));

Output:

09

Or you can use String.format() as well:

String format = "%1$02d"; // two digits
textView.setText(String.format(format, time));

Solution 2:

Use: text.setText(String.format("%02d", i)); where i is the integer value

Solution 3:

Why not just use an if statement?

Stringstr = x < 10 ? "0" + String.valueOf(x) : String.valueOf(x);

That should do the trick.

Solution 4:

TextView time; 
inthour=0,minute=0,second=0;
time.setText((String.format("%02d", hour))+":"+(String.format("%02d", minute))+":"+(String.format("%02d", second)));

time to TextView

Solution 5:

Try using this:

tv.setText(new DecimalFormat("##").format(var));

Post a Comment for "How To Format Longs In Android To Always Display Two Digits"