如何在Android中设置长整型以始终显示两位数 [英] How to format longs in android to always display two digits

查看:491
本文介绍了如何在Android中设置长整型以始终显示两位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想要一个等价的 String.format(%2d,1)

解决方案

您可以使用DeclimalFormat

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

输出:

  09 

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

 字符串格式=%1 $ 02d; //两个数字
textView.setText(String.format(format,time));


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)

解决方案

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));

这篇关于如何在Android中设置长整型以始终显示两位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆