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

2ekbmq32  于 2022-12-28  发布在  其他
关注(0)|答案(3)|浏览(223)

如何在jsp中将数字转换为K千M百万和B十亿后缀
例如,
1111作为1.111 K

2g32fytz

2g32fytz1#

把这里的答案改编一下,应该看起来像

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));
}

测试代码:

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

输出:

0:        0
                  27:       27
                 999:      999
                1000:    1.0 k
              110592:  110.6 k
         28991029248:   29.0 G
 9223372036854775807:    9.2 E
crcmnpdw

crcmnpdw2#

//从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));
    }
kr98yfug

kr98yfug3#

public String converter(double number) {
    Map<String, Double> suffixes = new HashMap<>();
    suffixes.put("K", 1000.0);
    suffixes.put("L", 100000.0);
    suffixes.put("M", 1000000.0);
    suffixes.put("Cr", 10000000.0);
    suffixes.put("B", 1000000000.0);
    suffixes.put("T", 1000000000000.0);

    for (Map.Entry<String, Double> entry : suffixes.entrySet()) {
        if (Math.abs(number) >= entry.getValue()) {
            number = number / entry.getValue();
            return DECIMAL_FORMAT.format(number) + entry.getKey();
        }
    }

    return DECIMAL_FORMAT.format(number);
}

相关问题