How to format longs in android to always display two digits How to format longs in android to always display two digits android android

How to format longs in android to always display two digits


You can accomplish it with DecimalFormat:

NumberFormat f = new DecimalFormat("00");long time = 9;textView.setText(f.format(time));

Output:

09

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

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


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


Why not just use an if statement?

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

That should do the trick.