How can I pad an integer with zeros on the left?

2018-12-31 01:36发布

How do you left pad an int with zeros when converting to a String in java?

I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).

14条回答
低头抚发
2楼-- · 2018-12-31 02:06

Try this one:

DecimalFormat df = new DecimalFormat("0000");
String c = df.format(9);   // 0009
String a = df.format(99);  // 0099
String b = df.format(999); // 0999
查看更多
心情的温度
3楼-- · 2018-12-31 02:08
public static String zeroPad(long number, int width) {
   long wrapAt = (long)Math.pow(10, width);
   return String.valueOf(number % wrapAt + wrapAt).substring(1);
}

The only problem with this approach is that it makes you put on your thinking hat to figure out how it works.

查看更多
余生无你
4楼-- · 2018-12-31 02:10

Check my code that will work for integer and String.

Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code

    int number=2;
    int requiredLengthAfterPadding=4;
    String resultString=Integer.toString(number);
    int inputStringLengh=resultString.length();
    int diff=requiredLengthAfterPadding-inputStringLengh;
    if(inputStringLengh<requiredLengthAfterPadding)
    {
        resultString=new String(new char[diff]).replace("\0", "0")+number;
    }        
    System.out.println(resultString);
查看更多
心情的温度
5楼-- · 2018-12-31 02:13

Use the class DecimalFormat, like so:

NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another number
System.out.println("OUTPUT : "+formatter.format(811)); 

OUTPUT : 0000811

查看更多
倾城一夜雪
6楼-- · 2018-12-31 02:13

No packages needed:

String paddedString = i < 100 ? i < 10 ? "00" + i : "0" + i : "" + i;

This will pad the string to three characters, and it is easy to add a part more for four or five. I know this is not the perfect solution in any way (especially if you want a large padded string), but I like it.

查看更多
流年柔荑漫光年
7楼-- · 2018-12-31 02:16

Although many of the above approaches are good, but sometimes we need to format integers as well as floats. We can use this, particularly when we need to pad particular number of zeroes on left as well as right of decimal numbers.

import java.text.NumberFormat;  
public class NumberFormatMain {  

public static void main(String[] args) {  
    int intNumber = 25;  
    float floatNumber = 25.546f;  
    NumberFormat format=NumberFormat.getInstance();  
    format.setMaximumIntegerDigits(6);  
    format.setMaximumFractionDigits(6);  
    format.setMinimumFractionDigits(6);  
    format.setMinimumIntegerDigits(6);  

    System.out.println("Formatted Integer : "+format.format(intNumber).replace(",",""));  
    System.out.println("Formatted Float   : "+format.format(floatNumber).replace(",",""));  
 }    
}  
查看更多
登录 后发表回答