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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20293887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:54:31  来源:igfitidea点击:

How to format longs in android to always display two digits

javaandroidformatting

提问by Akshat Agarwal

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.

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

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

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

采纳答案by Simon Dorociak

You can accomplish it with DecimalFormat:

您可以使用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()

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

回答by Joel Fernandes

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

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

回答by CodeWarrior

Try using this:

尝试使用这个:

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

回答by jonstaff

Why not just use an if statement?

为什么不直接使用 if 语句?

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

That should do the trick.

这应该够了吧。

回答by Sander Berloo van

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

time to TextView

文本视图的时间