2013-07-17 30 views
11

我想将一个3位integer格式化为4位数string值。例如:如何将3位整数格式化为4位数字符串?

int a = 800; 
String b = "0800"; 

当然格式化将在String b语句完成。多谢你们!

+3

看看http://docs.oracle.com/javase/tutorial/java/data/numberformat.html – arynaq

+0

@arynaq thx!这非常有帮助! –

回答

29

使用String#format

String b = String.format("%04d", a); 

对于其它的格式请参documentation

+0

明白了,谢谢! –

+0

废话,差不多24小时,我完全忘记接受这个答案!我的错! –

3
String b = "0" + a; 

难道是更容易?

+0

@SandiipPatil那不会编译。 –

+1

它会更容易吗?不,但可能更强大/灵活。 – Thilo

+2

@Thilo:同意。但问题特别要求3位整数。为什么当事情变得简单时就让事情变得复杂?现在,我也同意你的解决方案远非如此复杂:-) –

1

请尝试

String.format("%04d", b); 
+1

在'b'旁边而不是'a',这个答案与Thilo的答案有什么不同? – Maroun

+0

@MarounMaroun:好吧,看看时间戳。最有可能只是一个竞争条件。 – Thilo

5

如果你想拥有它只有一次使用String.format("%04d", number) - 如果你需要更频繁并希望集中模式(例如配置文件),请参阅下面的解决方案。

Btw。数字格式有一个Oracle tutorial

要长话短说:

import java.text.*; 

public class Demo { 

    static public void main(String[] args) { 
     int value = 123; 
     String pattern="0000"; 
     DecimalFormat myFormatter = new DecimalFormat(pattern); 
     String output = myFormatter.format(value); 
     System.out.println(output); //
    } 
} 

希望有所帮助。 * Jost

+0

实际上,这可能会稍微好一些。 –

0

您可以随时使用Jodd Printf。在你的情况下:

Printf.str("%04d", 800); 

会做这项工作。这个类是在Sun添加String.format之前创建的,并且有更多的格式选项。

相关问题