Search code examples
javaif-statementnumber-formatting

How do I Input comma sign without Number format in java


I wrote this code with out number format class. My Question Is: Is there any way to make this process shorter without Number Format Class.

String num=JOptionPane.showInputDialog("enter number");
Int len=num.length();
String res="";

if (len==4){
res=num.charAt(0)+","+num.substring(1);

}

else if(len==5){
res=num.substring(0,2)+","+num.substring(2);
}

else if(len==6){
res=num.substring(0,3)+","+num.substring(3);
}

else if(len==7){
res=num.charAt(0)+","+num.substring(1,4)+","+num.substring(4);
}

else if(len==8){
res=num.substring(0,2)+","+num.substring(2,5)+","+num.substring(5);
}

else if(len==9){
res=num.substring(0,3)+","+num.substring(3,6)+","+num.substring(6);
}

else if(len==10){
res=num.charAt(0)+","+num.substring(1,4)+","+num.substring(4,7)+","+num.substring(7);
}

System.out.println(res);

Solution

  • Something like the following:

    public static void main(String[] args) {
            int myInt = 1234567890;
            StringBuilder str = new StringBuilder(String.valueOf(myInt));
    
            int length = str.length();
            int count = 0;
    
            for (int i = length; i > 0; i--) {
                count++;
    
                if (count % 3 == 0 && count != length) {                
                    str.insert(i - 1, ",");
                } 
            }
            System.out.println("Formatted Number: " + str);
    
        }