java 如何格式化长数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3672955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:57:35  来源:igfitidea点击:

How to format long numbers?

javanumbersnumber-formatting

提问by Sheehan Alam

If I have a number that is 100,000,000 how can I represent that as "100M" in a string?

如果我有一个 100,000,000 的数字,我如何在字符串中将其表示为“100M”?

采纳答案by Aaron Novstrup

To my knowledge there's no library support for abbreviating numbers, but you can easily do it yourself:

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

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

Of course, this assumes that you don't want to shorten a number like 1,234,567.89. If you do, then this question is a duplicate.

当然,这假设您不想缩短像 1,234,567.89 这样的数字。如果你这样做,那么这个问题是重复的

回答by sled

There is an algorithm to do that:

有一种算法可以做到这一点:

You need a map that looks like

你需要一张看起来像的地图

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

... and so on...

... 等等...

1) Take the number "num", calculate the log10 exponent "ex" of the number and floor it.

1) 取数字“num”,计算该数字的log10指数“ex”并取下它。

Attention

log10(0) doesn't exist so check that the number is not 0 and since it doesn't make sense to output something like 20 = "2 ten" you should return the number as it is if it's smaller than 100 !

注意力

log10(0) 不存在,因此请检查该数字是否不为 0 并且由于输出 20 = "2十" 之类的内容没有意义,因此您应该按原样返回该数字,如果它小于 100 !

2) Now iterate thru the keys of the hash map above and look if a key matches, if not take the key that is smaller than the exponent "ex".

2)现在遍历上面散列映射的键并查看键是否匹配,如果不匹配,则使用小于指数“ex”的键。

3) Update "ex" to this key!

3)将“ex”更新为这个键!

4) Now format the number like

4)现在将数字格式化为

num = num / pow(10, ex)

num = num / pow(10, ex)

(!! ex is a key of the hash map !!)

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

5) now you could round the number to a certain precision and output num + yourHash[ex]

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

An example:

一个例子:

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

回答by phreakhead

Here's my solution to make it a little more generic:

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

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

回答by Javanator

This is more general solution.

这是更通用的解决方案。

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