How to add leading zeros to negative number in Java

2 Answers

0 votes
public class MyClass {
    public static String AddLeadingZerosToNegativeNumber(int num, int digits) {
        boolean negative = false;
        
        if (num < 0) {
            num *= -1;
            negative = true;
        }
        
        String s = Integer.toString(num);
        
        while (s.length() < digits) {
            s = "0" + s;
        }
        
        if (negative) {
            return "-" + s;
        }
        
        return s;
    }

    public static void main(String args[]) {
        int num = -5;

        System.out.println(AddLeadingZerosToNegativeNumber(num, 3));
    }
}
 
 
 
/*
run:
 
-005
 
*/

 



answered Jul 1, 2023 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        int num = -5;
 
        String s = String.format("%04d", num);
        
        System.out.println(s);
    }
}
  
  
  
/*
run:
  
-005
  
*/

 



answered Apr 16, 2024 by avibootz
...