如何格式化类似堆栈溢出声誉格式的数字
我想将一个数字转换成一个类似Stack Overflow声望显示的格式的string表示。
例如
- 999 =='999'
- 1000 =='1,000'
- 9999 =='9,999'
- 10000 =='10k'
- 10100 == '10 .1k'
另一种产生准确输出的方法:
function getRepString (rep) { rep = rep+''; // coerce to string if (rep < 1000) { return rep; // return the same number } if (rep < 10000) { // place a comma between return rep.charAt(0) + ',' + rep.substring(1); } // divide and format return (rep/1000).toFixed(rep % 1000 != 0)+'k'; }
在这里检查输出结果。
更新 :CMS得到了检查,并提供了一个优越的答案。 以他的方式发送更多的选票。
// formats a number similar to the way stack exchange sites // format reputation. eg // for numbers< 10000 the output is '9,999' // for numbers > 10000 the output is '10k' with one decimal place when needed function getRepString(rep) { var repString; if (rep < 1000) { repString = rep; } else if (rep < 10000) { // removed my rube goldberg contraption and lifted // CMS version of this segment repString = rep.charAt(0) + ',' + rep.substring(1); } else { repString = (Math.round((rep / 1000) * 10) / 10) + "k" } return repString.toString(); }
输出:
-
getRepString(999)
=='999' -
getRepString(1000)
=='1,000' -
getRepString(9999)
=='9,999' -
getRepString(10000)
=='10k' -
getRepString(10100)
== '10 .1k'
这是PHP中的一个函数,它是iZend的一部分 – http://www.izend.org/en/manual/library/countformat :
function count_format($n, $point='.', $sep=',') { if ($n < 0) { return 0; } if ($n < 10000) { return number_format($n, 0, $point, $sep); } $d = $n < 1000000 ? 1000 : 1000000; $f = round($n / $d, 1); return number_format($f, $f - intval($f) ? 1 : 0, $point, $sep) . ($d == 1000 ? 'k' : 'M'); }
Handlebars.registerHelper("classNameHere",function(rep) { var repString; if (rep < 1000) { repString = rep; } else if (rep < 10000) { rep = String(rep); r = rep.charAt(0); s = rep.substring(1); repString = r + ',' + s; } else { repDecimal = Math.round(rep / 100) / 10; repString = repDecimal + "k"; } return repString.toString(); });
这里是CMS的PHP 版本 (如果有人需要它,就像我一样):
function getRepString($rep) { $rep = intval($rep); if ($rep < 1000) { return (string)$rep; } if ($rep < 10000) { return number_format($rep); } return number_format(($rep / 1000), ($rep % 1000 != 0)) . 'k'; } // TEST var_dump(getRepString(999)); var_dump(getRepString(1000)); var_dump(getRepString(9999)); var_dump(getRepString(10000)); var_dump(getRepString(10100));
输出:
string(3) "999" string(5) "1,000" string(5) "9,999" string(3) "10k" string(5) "10.1k"
除以1000,如果结果大于1,则结束一个“k”。
如果结果小于1,只输出实际结果!
我创build了一个npm (和bower )模块来做到这一点:
npm install --save approximate-number
用法:
var approx = require('approximate-number'); approx(123456); // "123k"