如何在android中格式化longs以始终显示两位数

Aks*_*wal 14 java formatting android

我有一个倒计时器,显示从60到0的秒数(1分钟倒数计时器).当它达到1位数字,如9,8,7 ..它显示9而不是09.我尝试使用String.format("%[B]02d[/B]", x); 我将x从long转换为字符串的地方.它没用.

我想要相当于 String.format("%2d", 1)

Sim*_*iak 44

您可以使用DecimalFormat完成它:

NumberFormat f = new DecimalFormat("00");
long time = 9;
textView.setText(f.format(time));
Run Code Online (Sandbox Code Playgroud)

输出:

09
Run Code Online (Sandbox Code Playgroud)

或者您也可以使用String.format():

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


Joe*_*des 7

用途:text.setText(String.format(" %02d", i));这里i是整数值