How to convert number into K thousands M million and B billion suffix in jsp

前端 未结 2 2067
时光取名叫无心
时光取名叫无心 2020-12-13 03:01

How can i convert number into K thousands M million and B billion suffix in jsp

e.g

1111 as 1.111 K etc

相关标签:
2条回答
  • 2020-12-13 03:15

    Adapting the answer from over here it should look something like

    public static String withSuffix(long count) {
        if (count < 1000) return "" + count;
        int exp = (int) (Math.log(count) / Math.log(1000));
        return String.format("%.1f %c",
                             count / Math.pow(1000, exp),
                             "kMGTPE".charAt(exp-1));
    }
    

    Test code:

    for (long num : new long[] { 0, 27, 999, 1000, 110592,
                                 28991029248L, 9223372036854775807L })
       System.out.printf("%20d: %8s%n", num, withSuffix(num));
    

    Output:

                       0:        0
                      27:       27
                     999:      999
                    1000:    1.0 k
                  110592:  110.6 k
             28991029248:   29.0 G
     9223372036854775807:    9.2 E
    
    0 讨论(0)
  • 2020-12-13 03:32

    //To remove zero from 1.0k

    public static String coolNumberFormat(long count) {
            if (count < 1000) return "" + count;
            int exp = (int) (Math.log(count) / Math.log(1000));
            DecimalFormat format = new DecimalFormat("0.#");
            String value = format.format(count / Math.pow(1000, exp));
            return String.format("%s%c", value, "kMBTPE".charAt(exp - 1));
        }
    
    0 讨论(0)
提交回复
热议问题