如何将负数格式化为这样?
-5000 -> -5 k
-1000000 -> -1 M
-2700000000 -> -2.7 B
这是您可以使用的功能:
function format_number(num) {
var identifiers = ['k', 'M', 'B'];
var identifierLengthMinusOne = identifiers.length - 1;
var identifierOffset = -1;
var isNegative = (num < 0);
num = Math.abs(num);
while (num >= 1000 && identifierOffset < identifierLengthMinusOne) {
num /= 1000;
identifierOffset++;
}
return (isNegative ? num * -1 : num) + (identifierOffset > -1 ? ' ' + identifiers[identifierOffset] : '');
}
> format_number(-500)
"-500"
> format_number(-50000)
"-50 k"
> format_number(-50000000)
"-50 M"
> format_number(-50000000000)
"-50 B"
> format_number(-50000000000000)
"-50000 B"
检查这个:
function intToString (value) {
var suffixes = ["", "k", "m", "b","t"];
var suffixNum = Math.floor((""+value).length/3);
var shortValue = parseFloat((suffixNum != 0 ? (value / Math.pow(1000,suffixNum)) : value).toPrecision(2));
if (shortValue % 1 != 0) shortNum = shortValue.toFixed(1);
return shortValue+suffixes[suffixNum];
}
用法:
intToString (-5000)