Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.format("%[B]02d[/B]", x); where I converted x from long to string. It didn't work.

I want an equivalent of String.format("%2d", 1)

like image 326
Akshat Agarwal Avatar asked Nov 29 '13 21:11

Akshat Agarwal


People also ask

How to get only 2 digits after decimal in Java?

printf("%. 2f", value); The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (.

What is string format in Java?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Syntax: There is two types of string format() method.

Does string format round Java?

The String. format() method is typically to format a string in Java. It can also be used for rounding a double number to 2 decimal places.


2 Answers

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 digits
textView.setText(String.format(format, time));
like image 56
Simon Dorociak Avatar answered Sep 27 '22 15:09

Simon Dorociak


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

like image 31
Joel Fernandes Avatar answered Sep 27 '22 17:09

Joel Fernandes