【发布时间】:2011-02-11 03:34:15
【问题描述】:
基于这个问题:Is there a way to round numbers into a friendly format?
挑战 - 更新! (从规范中删除了数百个缩写)
按字符计数的最短代码,将缩写一个整数(无小数)。
代码应包含完整的程序。
相关范围为0 - 9,223,372,036,854,775,807(有符号64位整数的上限)。
缩写的小数位数为正数。 您不需要计算以下内容:920535 abbreviated -1 place(类似于0.920535M)。
十位和百位 (0-999) 的数字应永远缩写(数字 57 到 1+ 小数位的缩写为 5.7dk - 这是不必要的,并且不友好)。
记得从零取整一半(23.5 取整为 24)。银行家的四舍五入是禁止的。
以下是相关的数字缩写:
h = hundred (102)k = thousand (103)
@987654335 @6)G = billion (109)T = trillion (1012@ 987654343@P = quadrillion (1015)E = quintillion (1018)
SAMPLE INPUTS/OUTPUTS(输入可以作为单独的参数传递):
第一个参数将是要缩写的整数。第二个是小数位数。
12 1 => 12 // tens and hundreds places are never rounded
1500 2 => 1.5k
1500 0 => 2k // look, ma! I round UP at .5
0 2 => 0
1234 0 => 1k
34567 2 => 34.57k
918395 1 => 918.4k
2134124 2 => 2.13M
47475782130 2 => 47.48G
9223372036854775807 3 => 9.223E
// ect...
相关问题的原始答案(JavaScript,不遵循规范):
function abbrNum(number, decPlaces) {
// 2 decimal places => 100, 3 => 1000, etc
decPlaces = Math.pow(10,decPlaces);
// Enumerate number abbreviations
var abbrev = [ "k", "m", "b", "t" ];
// Go through the array backwards, so we do the largest first
for (var i=abbrev.length-1; i>=0; i--) {
// Convert array index to "1000", "1000000", etc
var size = Math.pow(10,(i+1)*3);
// If the number is bigger or equal do the abbreviation
if(size <= number) {
// Here, we multiply by decPlaces, round, and then divide by decPlaces.
// This gives us nice rounding to a particular decimal place.
number = Math.round(number*decPlaces/size)/decPlaces;
// Add the letter for the abbreviation
number += abbrev[i];
// We are done... stop
break;
}
}
return number;
}
【问题讨论】:
-
(1) 由于您的“相关缩写”是 k、M、G、T 等,因此您的示例输出应更改以匹配。 (2) 代码是否应该包含完整的程序?
-
如果构建一个完整的(而不是代码高尔夫)实现需要考虑两个问题:1)在某些情况下,2^10 比 10^3 作为基础更有意义,2)应该 xxx5 舍入甚至(更好的统计数据)而不是总是向上(简单规则)。我正在为实现其中一个(或两个)的答案投票。
-
@dmckee:我很难按原样制定规则。因此,我投票支持最简单的实现,以使其尽可能保持 Code-Golfy。
-
如果你想要二进制,请使用
44.22Gi:p -
我会投票删除数百个作为缩写的可能性。我在实践中从未见过这样做,而且它使代码复杂化,因为它不是 10 的 3 倍。
标签: language-agnostic code-golf rosetta-stone number-formatting human-readable