java 为数字添加前缀,例如 (1 = 001)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12745297/
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-10-31 10:02:32  来源:igfitidea点击:

Add prefix to number e.g (1 = 001)

java

提问by Antarix

Possible Duplicate:
Add leading zeroes to number in Java?

可能的重复:
在 Java 中向数字添加前导零?

I want to add prefix to my number. I have number which i want to convert it in 3 digits e.g if i pass 1 than it should return 001. Here is my code.

我想为我的号码添加前缀。我有我想将其转换为 3 位数字的数字,例如,如果我传递 1 比它应该返回 001。这是我的代码。

public int returnThreeDigitNo(int number)
{
    int threeDigitNo = 0;
    int length = String.valueOf(number).length();
    if(length == 1)
    {
        threeDigitNo = 00+number;
    }
    if(length == 2)
    {
        threeDigitNo = 0+number;
    }
    if(length == 3)
    {
        threeDigitNo = number;
    }
    return threeDigitNo;
}

thanks in advance

提前致谢

回答by Jochem Gruter

If you want to display an int with 3 digits you can use:

如果要显示 3 位整数,可以使用:

String.format("%03d", yournumber);