我需要显示一个货币值的格式1K等于一千,或1.1K, 1.2K, 1.9K等,如果它不是一个偶数千,否则如果低于一千,显示正常500,100,250等,使用JavaScript格式化的数字?
当前回答
不满足任何张贴的解决方案,所以这是我的版本:
Supports positive and negative numbers Supports negative exponents Rounds up to next exponent if possible Performs bounds checking (doesn't error out for very large/small numbers) Strips off trailing zeros/spaces Supports a precision parameter function abbreviateNumber(number,digits=2) { var expK = Math.floor(Math.log10(Math.abs(number)) / 3); var scaled = number / Math.pow(1000, expK); if(Math.abs(scaled.toFixed(digits))>=1000) { // Check for rounding to next exponent scaled /= 1000; expK += 1; } var SI_SYMBOLS = "apμm kMGTPE"; var BASE0_OFFSET = SI_SYMBOLS.indexOf(' '); if (expK + BASE0_OFFSET>=SI_SYMBOLS.length) { // Bound check expK = SI_SYMBOLS.length-1 - BASE0_OFFSET; scaled = number / Math.pow(1000, expK); } else if (expK + BASE0_OFFSET < 0) return 0; // Too small return scaled.toFixed(digits).replace(/(\.|(\..*?))0+$/,'$2') + SI_SYMBOLS[expK+BASE0_OFFSET].trim(); } ////////////////// const tests = [ [0.0000000000001,2], [0.00000000001,2], [0.000000001,2], [0.000001,2], [0.001,2], [0.0016,2], [-0.0016,2], [0.01,2], [1,2], [999.99,2], [999.99,1], [-999.99,1], [999999,2], [999999999999,2], [999999999999999999,2], [99999999999999999999,2], ]; for (var i = 0; i < tests.length; i++) { console.log(abbreviateNumber(tests[i][0], tests[i][1]) ); }
其他回答
以下是我对韦伦·弗林的回答的看法。这将删除.0并修复当层不是整数时的未定义。
const SI_SYMBOL = ['', 'k', 'M', 'G', 'T', 'P', 'E'];
abbreviateNumber(num) {
const tier = Math.floor(Math.log10(num) / 3) || 0;
let result = '' + num;
// if zero, we don't need a suffix
if (tier > 0) {
// get suffix and determine scale
const suffix = SI_SYMBOL[tier];
const scale = Math.pow(10, tier * 3);
// scale the number
const scaled = num / scale;
// format number and add suffix
result = scaled.toFixed(1).replace('.0', '') + suffix;
}
return result;
}
这个函数可以将巨大的数字(正数和负数)转换为读者友好的格式,而不会失去其精度:
function abbrNum(n) { if (!n || (n && typeof n !== 'number')) { return ''; } const ranges = [ { divider: 1e12 , suffix: 't' }, { divider: 1e9 , suffix: 'b' }, { divider: 1e6 , suffix: 'm' }, { divider: 1e3 , suffix: 'k' } ]; const range = ranges.find(r => Math.abs(n) >= r.divider); if (range) { return (n / range.divider).toString() + range.suffix; } return n.toString(); } /* test cases */ let testAry = [99, 1200, -150000, 9000000]; let resultAry = testAry.map(abbrNum); console.log("result array: " + resultAry);
一个更普遍的版本:
function nFormatter(num, digits) { const lookup = [ { value: 1, symbol: "" }, { value: 1e3, symbol: "k" }, { value: 1e6, symbol: "M" }, { value: 1e9, symbol: "G" }, { value: 1e12, symbol: "T" }, { value: 1e15, symbol: "P" }, { value: 1e18, symbol: "E" } ]; const rx = /\.0+$|(\.[0-9]*[1-9])0+$/; var item = lookup.slice().reverse().find(function(item) { return num >= item.value; }); return item ? (num / item.value).toFixed(digits).replace(rx, "$1") + item.symbol : "0"; } /* * Tests */ const tests = [ { num: 0, digits: 1 }, { num: 12, digits: 1 }, { num: 1234, digits: 1 }, { num: 100000000, digits: 1 }, { num: 299792458, digits: 1 }, { num: 759878, digits: 1 }, { num: 759878, digits: 0 }, { num: 123, digits: 1 }, { num: 123.456, digits: 1 }, { num: 123.456, digits: 2 }, { num: 123.456, digits: 4 } ]; tests.forEach(function(test) { console.log("nFormatter(" + test.num + ", " + test.digits + ") = " + nFormatter(test.num, test.digits)); });
function AmountConveter(amount) {
return Math.abs(amount) > 999
? Math.sign(amount) * (Math.abs(amount) / 1000).toFixed(1) + "k"
: Math.sign(amount) * Math.abs(amount);
}
console.log(AmountConveter(1200)); // 1.2k
console.log(AmountConveter(-1200)); // -1.2k
console.log(AmountConveter(900)); // 900
console.log(AmountConveter(-900)); // -900
进一步改进@Yash的回答,支持负数:
function nFormatter(num) {
isNegative = false
if (num < 0) {
isNegative = true
}
num = Math.abs(num)
if (num >= 1000000000) {
formattedNumber = (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
} else if (num >= 1000000) {
formattedNumber = (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
} else if (num >= 1000) {
formattedNumber = (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
} else {
formattedNumber = num;
}
if(isNegative) { formattedNumber = '-' + formattedNumber }
return formattedNumber;
}
nFormatter(-120000)
"-120K"
nFormatter(120000)
"120K"
推荐文章
- 如何在Typescript中解析JSON字符串
- jQuery的“输入”事件
- Javascript reduce()在对象
- 在angularJS中& vs @和=的区别是什么
- 错误"Uncaught SyntaxError:意外的标记与JSON.parse"
- JavaScript中的querySelector和querySelectorAll vs getElementsByClassName和getElementById
- 给一个数字加上st, nd, rd和th(序数)后缀
- 如何以编程方式触发引导模式?
- setTimeout带引号和不带括号的区别
- 在JS的Chrome CPU配置文件中,'self'和'total'之间的差异
- 用javascript检查输入字符串中是否包含数字
- 如何使用JavaScript分割逗号分隔字符串?
- 在Javascript中~~(“双波浪号”)做什么?
- 谷歌chrome扩展::console.log()从后台页面?
- 未捕获的SyntaxError: