Code Optimization

Interesting things about software development and code optimization

Format a string to set comma delimited for every thousand

Hello friends,


as the title reads here is the easy way to put comma for every thousand in your string:

String mileage = "1234567";
String newMileage = mileage;
for (int i = 1; i <= (mileage.length) / 3; i++) {
    if (newMileage.length - (i * 3) - (i - 1) > 0) {
        newMileage = newMileage.substring(
                    0, newMileage.length - (i * 3) - (i - 1)) +
                    "," +
                    newMileage.substring(newMileage.length - (i * 3) - (i - 1));
     }
}

the output will be like that:

123
1,234
1,234,567
...


Thank you and see you :)


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y