How can I format a String number to have commas in android Edit Field

后端 未结 8 1802
盖世英雄少女心
盖世英雄少女心 2020-12-07 18:27

For what function I can use in android to display the number into different formats.

For eg: If I enter 1000 then it should display like this 1,000. If I enter 1000

相关标签:
8条回答
  • 2020-12-07 19:09
    int[] numbersToFormat = new int[]
      { 1, 10, 100, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
    
    
    for (int number : numbersToFormat) {
      System.out.println(  
        NumberFormat.getNumberInstance(Locale.getDefault()).format(number));
    }
    

    OUTPUT

    1
    10
    100
    10,000
    100,000
    1,000,000
    10,000,000
    100,000,000
    1,000,000,000
    
    0 讨论(0)
  • 2020-12-07 19:09

    Add this function in common class

      public static String getFormatedNumber(String number){
            if(!number.isEmpty()) {
                double val = Double.parseDouble(number);
                return NumberFormat.getNumberInstance(Locale.US).format(val);
            }else{
                return "0";
            }
        }
    

    And use that function every where like this:

    String newNumber = Utils.getFormatedNumber("10000000");
    
    0 讨论(0)
提交回复
热议问题