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

后端 未结 16 2259
南旧
南旧 2020-11-21 06:31

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

相关标签:
16条回答
  • 2020-11-21 06:46

    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.

    0 讨论(0)
  • 2020-11-21 06:47

    Try this one:

    import java.text.DecimalFormat; 
    
    DecimalFormat df = new DecimalFormat("0000");
    
    String c = df.format(9);   // Output: 0009
    
    String a = df.format(99);  // Output: 0099
    
    String b = df.format(999); // Output: 0999
    
    0 讨论(0)
  • 2020-11-21 06:48

    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

    0 讨论(0)
  • 2020-11-21 06:51

    You need to use a Formatter, following code uses NumberFormat

        int inputNo = 1;
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumIntegerDigits(4);
        nf.setMinimumIntegerDigits(4);
        nf.setGroupingUsed(false);
    
        System.out.println("Formatted Integer : " + nf.format(inputNo));
    

    Output: 0001

    0 讨论(0)
  • 2020-11-21 06:53
    int x = 1;
    System.out.format("%05d",x);
    

    if you want to print the formatted text directly onto the screen.

    0 讨论(0)
  • 2020-11-21 06:54

    Use java.lang.String.format(String,Object...) like this:

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

    for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".

    The full formatting options are documented as part of java.util.Formatter.

    0 讨论(0)
提交回复
热议问题