javaandroidandroid-studio

How to add comma every 3 digits without using number format?


I am trying to format a value,

Example:

1526374856.03

to:

1,526,374,856.03

Solution

  • To do it without using NumberFormat, you can convert the number to a String and do the following code:

    double number = 1526374856.03;
    String[] array = Double.toString(number).split(".");
    String numString = array[0];
    
    String newString = "";
    for(int i = 0; i < numString.length() ; i++){
        if((numString.length() - i - 1) % 3 == 0){
            newString += Character.toString(numString.charAt(i)) + ",";
        }else{
            newString += Character.toString(numString.charAt(i));
        }
    }
    newString += array[1];
    

    newString is now the new String that contains the number with the commas.