如何格式化长数字?

时间:2010-09-09 00:28:08

标签: java numbers number-formatting

如果我的数字是100,000,000,我怎么能在字符串中将其表示为“100M”?

4 个答案:

答案 0 :(得分:8)

据我所知,没有图书馆支持缩写数字,但你可以自己轻松完成:

NumberFormat formatter = NumberFormat.getInstance();
String result = null;
if (num % 1000000 == 0 && num != 0) {
   result = formatter.format(num / 1000000) + "M";
} else if (num % 1000 == 0 && num != 0) {
   result = formatter.format(num / 1000) + "K";
} else {
   result = formatter.format(num);
}

当然,这假设您不想缩短1,234,567.89之类的数字。如果你,那么这个问题是duplicate

答案 1 :(得分:3)

有一种算法可以做到:

您需要一张看起来像

的地图
2 => "hundred"
3 => "thousand"
6 => "million"
9 => "billion"
12 => "trillion"
15 => "quadrillion"

......等等......

1)取数字“num”,计算数字和地面的log10指数“ex”。

  

<强>注意

     

log10(0)不存在,请检查   数字不是0,因为它   输出一些东西是没有意义的   像20 =“2十”你应该回来   如果数量较小,则为数字   超过100!

2)现在通过上面的哈希映射的键迭代并查看键是否匹配,如果不匹配小于指数“ex”的键。

3)将“ex”更新为此键!

4)现在格式化数字

num = num / pow(10,ex)

(!! ex是哈希映射的关键!!)

5)现在你可以将数字四舍五入到一定的精度并输出num + yourHash[ex]

一个例子:

number = 12345.45
exponent = floor(log10(12345.45))

exponent should now be 4 !

look for a key in the hash map -- whoops no key matches 4 ! -- so take 3 !

set exponent to 3 

now you scale the number:

number = number / pow(10, exponent)

number = 12345.45 / pow(10, 3) 

number = 12345.45 / 1000

number is now 12.34545

now you get the value to the corresponding key out of the hash map

the value to the key, which is 3 in this example, is thousand  

so you output 12.34545 thousand

答案 2 :(得分:1)

这是我的解决方案,使其更通用:

private static final String[] magnitudes = new String[] {"", "K", "M"};

public static String shortenNumber(final Integer num) {
    if (num == null || num == 0) 
        return "0";

    float res = num;
    int i = 0;
    for (; i < magnitudes.length; i++) {
        final float sm = res / 1000;
        if (sm < 1) break;

        res = sm;
    }


    // don't use fractions if we don't have to
    return ( (res % (int) res < 0.1) ?
                String.format("%d", (int)res) :
                String.format("%.1f", res)
            ) 
            + magnitudes[i];
}

答案 3 :(得分:0)

这是更通用的解决方案。

public static String abbreviateNumber(long num) {

    long temp = num / 1000000; 
    if(temp > 0) {
        return temp + "M+";
    }

    temp = num / 1000;
    if (temp > 0) {
        return temp + "K+";
    }

    temp = num / 500;
    if (temp > 0) {
        return  "500+";
    }

    temp = num / 100;
    if (temp > 0) {
        return  "100+";
    }

    temp = num / 50;
    if (temp > 0) {
        return  "50+";
    }

    temp = num / 10;
    if (temp > 0) {
        return  "10+";
    }

    return String.valueOf(num);
}