如果我有一个 100,000,000 的数字,我如何在字符串中将其表示为“100M”?
问问题
12415 次
4 回答
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 这样的数字。如果你这样做了,那么这个问题就是重复的。
于 2010-09-09T00:45:02.190 回答
3
有一种算法可以做到这一点:
你需要一张看起来像的地图
2 => "hundred"
3 => "thousand"
6 => "million"
9 => "billion"
12 => "trillion"
15 => "quadrillion"
... 等等...
1) 取数字“num”,计算该数字的 log10 指数“ex”并将其取底。
注意力
log10(0) 不存在,因此请检查该数字是否不为 0,并且由于输出 20 = "2 ten" 之类的内容没有意义,因此如果它小于 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
于 2010-09-09T01:09:46.780 回答
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];
}
于 2013-04-09T22:17:58.513 回答
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);
}
于 2016-02-19T06:48:12.147 回答