如何在jsp中将数字转换为K千万M和B亿后缀

jan*_*an5 18 java jsp

如何在jsp中将数字转换为K千万M和B亿后缀

例如

1111作为1.111 K

aio*_*obe 78

这里调整答案应该看起来像

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));
}
Run Code Online (Sandbox Code Playgroud)

测试代码:

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

输出:

                   0:        0
                  27:       27
                 999:      999
                1000:    1.0 k
              110592:  110.6 k
         28991029248:   29.0 G
 9223372036854775807:    9.2 E
Run Code Online (Sandbox Code Playgroud)

  • @BeeingJk这里公共静态字符串coolNumberFormat(long count){if(count &lt;1000)return“” + count; int exp =(int)(Math.log(count)/ Math.log(1000)); DecimalFormat格式=新的DecimalFormat(“ 0.#”); 字符串值= format.format(count / Math.pow(1000,exp)); return String.format(“%s%c”,value,“ kMBTPE” .charAt(exp-1)); } (2认同)

use*_*347 5

//从 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));
    }
Run Code Online (Sandbox Code Playgroud)