我需要显示一个货币值的格式1K等于一千,或1.1K, 1.2K, 1.9K等,如果它不是一个偶数千,否则如果低于一千,显示正常500,100,250等,使用JavaScript格式化的数字?
当前回答
这个函数可以将巨大的数字(正数和负数)转换为读者友好的格式,而不会失去其精度:
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);
其他回答
我用的是这个函数。它适用于php和javascript。
/**
* @param $n
* @return string
* Use to convert large positive numbers in to short form like 1K+, 100K+, 199K+, 1M+, 10M+, 1B+ etc
*/
function num_format($n) {
$n_format = null;
$suffix = null;
if ($n > 0 && $n < 1000) {
$n_format = Math.floor($n);
$suffix = '';
}
else if ($n == 1000) {
$n_format = Math.floor($n / 1000); //For PHP only use floor function insted of Math.floor()
$suffix = 'K';
}
else if ($n > 1000 && $n < 1000000) {
$n_format = Math.floor($n / 1000);
$suffix = 'K+';
} else if ($n == 1000000) {
$n_format = Math.floor($n / 1000000);
$suffix = 'M';
} else if ($n > 1000000 && $n < 1000000000) {
$n_format = Math.floor($n / 1000000);
$suffix = 'M+';
} else if ($n == 1000000000) {
$n_format = Math.floor($n / 1000000000);
$suffix = 'B';
} else if ($n > 1000000000 && $n < 1000000000000) {
$n_format = Math.floor($n / 1000000000);
$suffix = 'B+';
} else if ($n == 1000000000000) {
$n_format = Math.floor($n / 1000000000000);
$suffix = 'T';
} else if ($n >= 1000000000000) {
$n_format = Math.floor($n / 1000000000000);
$suffix = 'T+';
}
/***** For PHP ******/
// return !empty($n_format . $suffix) ? $n_format . $suffix : 0;
/***** For Javascript ******/
return ($n_format + $suffix).length > 0 ? $n_format + $suffix : 0;
}
这个函数可以将巨大的数字(正数和负数)转换为读者友好的格式,而不会失去其精度:
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);
这篇文章很旧了,但我不知何故找到了这篇文章。所以添加我的输入数字js是一站式的解决方案现在一天。它提供了大量的方法来帮助格式化数字
http://numeraljs.com/
哇,这里有这么多答案。我想我会告诉你我是如何解决它的,因为它似乎是最容易阅读的,处理负数,并且在JavaScript的千位数范围内。它也很容易改变到你想要的或进一步扩展。
const symbols = [ { 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' } ]; function numberFormatter(num, digits) { const numToCheck = Math.abs(num); for (let i = symbols.length - 1; i >= 0; i--) { if (numToCheck >= symbols[i].value) { const newNumber = (num / symbols[i].value).toFixed(digits); return `${newNumber}${symbols[i].symbol}`; } } return '0'; } const tests = [ { 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 } ]; for (let i = 0; i < tests.length; i++) { console.log(`numberFormatter(${tests[i].num}, ${tests[i].digits})=${numberFormatter(tests[i].num, tests[i].digits)}`); }
不满足任何张贴的解决方案,所以这是我的版本:
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]) ); }
推荐文章
- 如何在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: