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

后端 未结 16 2268
南旧
南旧 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 07:10

    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(",",""));  
     }    
    }  
    

提交回复
热议问题