我要獲得這個格式的字符串:我怎麼能在JAVA
"000xxx"
一些示例:
int xxx = 10 -> result = "000010";
int xxx = 015 -> result = "000015";
int xxx = 100 -> result = "000100";
我可以使用哪些格式化爲一個字符串?
我要獲得這個格式的字符串:我怎麼能在JAVA
"000xxx"
一些示例:
int xxx = 10 -> result = "000010";
int xxx = 015 -> result = "000015";
int xxx = 100 -> result = "000100";
我可以使用哪些格式化爲一個字符串?
您可以使用追加留下String.format
例如:
int myInt = 1;
String result = String.format("%06d", myInt);
輸出
1 000001
10 000010
101 000101
爲什麼你使用一個字符串,如果你Integer.parseInt它後無論如何:p – Nathan
是的,我不知道什麼OP使用類型,謝謝任何方式@Nathan –
System.out.format("%06d", n);
,其中n
是一個整數,應該工作正常進行您的格式。它看起來是6位寬度,帶領0
's。與其他答案一樣,如果您只是在尋找字符串,您可以僅執行String.format("%06d", n);
。
這可能會幫助;
static String getString(int xxx)
{
if(xxx > 0 && xxx < 1000)
return String.format("%06d", xxx);
return null;
}
public class Temp {
public static void main(String args[]) {
System.out.println(StringReturn.numToString(1));
System.out.println(StringReturn.numToString(10));
System.out.println(StringReturn.numToString(101));
}}
class StringReturn
{
static String numToString(int num){
return String.format("%06d", num);
}}
輸出
000001
000010
000101
https://docs.oracle.com/javase/tutorial/java/data/numberformat.html –
第一次嘗試。如果您遇到問題,請提出一個**特定的**問題,以及您將寫入的(錯誤)代碼。 – progyammer