我需要显示一个货币值的格式1K等于一千,或1.1K, 1.2K, 1.9K等,如果它不是一个偶数千,否则如果低于一千,显示正常500,100,250等,使用JavaScript格式化的数字?
当前回答
韦伦·弗林解决方案的2020版。
const SI_SYMBOLS = ["", "k", "M", "G", "T", "P", "E"];
const abbreviateNumber = (number, minDigits, maxDigits) => {
if (number === 0) return number;
// determines SI symbol
const tier = Math.floor(Math.log10(Math.abs(number)) / 3);
// get suffix and determine scale
const suffix = SI_SYMBOLS[tier];
const scale = 10 ** (tier * 3);
// scale the number
const scaled = number / scale;
// format number and add suffix
return scaled.toLocaleString(undefined, {
minimumFractionDigits: minDigits,
maximumFractionDigits: maxDigits,
}) + suffix;
};
Tests and examples: const abbreviateNumberFactory = (symbols) => ( (number, minDigits, maxDigits) => { if (number === 0) return number; // determines SI symbol const tier = Math.floor(Math.log10(Math.abs(number)) / 3); // get suffix and determine scale const suffix = symbols[tier]; const scale = 10 ** (tier * 3); // scale the number const scaled = number / scale; // format number and add suffix return scaled.toLocaleString(undefined, { minimumFractionDigits: minDigits, maximumFractionDigits: maxDigits, }) + suffix; } ); const SI_SYMBOLS = ["", "k", "M", "G", "T", "P", "E"]; const SHORT_SYMBOLS = ["", "K", "M", "B", "T", "Q"]; const LONG_SYMBOLS = ["", " thousand", " million", " billion", " trillion", " quadrillion"]; const abbreviateNumberSI = abbreviateNumberFactory(SI_SYMBOLS); const abbreviateNumberShort = abbreviateNumberFactory(SHORT_SYMBOLS); const abbreviateNumberLong = abbreviateNumberFactory(LONG_SYMBOLS); const tests = [1e5, -9e7, [1009999.999, 2], [245345235.34513, 1, 1], [-72773144123, 3] ]; const functions = { abbreviateNumberSI, abbreviateNumberShort, abbreviateNumberLong, }; tests.forEach((test) => { const testValue = Array.isArray(test) ? test : [test]; Object.entries(functions).forEach(([key, func]) => { console.log(`${key}(${testValue.join(', ')}) = ${func(...testValue)}`); }); });
其他回答
我认为这是一个解决方案。
var unitlist = ["","K","M","G"]; function formatnumber(number){ let sign = Math.sign(number); let unit = 0; while(Math.abs(number) > 1000) { unit = unit + 1; number = Math.floor(Math.abs(number) / 100)/10; } console.log(sign*Math.abs(number) + unitlist[unit]); } formatnumber(999); formatnumber(1234); formatnumber(12345); formatnumber(123456); formatnumber(1234567); formatnumber(12345678); formatnumber(-999); formatnumber(-1234); formatnumber(-12345); formatnumber(-123456); formatnumber(-1234567); formatnumber(-12345678);
支持负数 检查!isFinite 如果你想要最大单位是M,将' K M G T P E Z Y'改为' K M' 基数选项(1K = 1000 / 1K = 1024)
Number.prototype.prefix = function (precision, base) { var units = ' K M G T P E Z Y'.split(' '); if (typeof precision === 'undefined') { precision = 2; } if (typeof base === 'undefined') { base = 1000; } if (this == 0 || !isFinite(this)) { return this.toFixed(precision) + units[0]; } var power = Math.floor(Math.log(Math.abs(this)) / Math.log(base)); // Make sure not larger than max prefix power = Math.min(power, units.length - 1); return (this / Math.pow(base, power)).toFixed(precision) + units[power]; }; console.log('0 = ' + (0).prefix()) // 0.00 console.log('10000 = ' + (10000).prefix()) // 10.00K console.log('1234000 = ' + (1234000).prefix(1)) // 1.2M console.log('-10000 = ' + (-10240).prefix(1, 1024)) // -10.0K console.log('-Infinity = ' + (-Infinity).prefix()) // -Infinity console.log('NaN = ' + (NaN).prefix()) // NaN
这篇文章很旧了,但我不知何故找到了这篇文章。所以添加我的输入数字js是一站式的解决方案现在一天。它提供了大量的方法来帮助格式化数字
http://numeraljs.com/
function transform(value,args) {
const suffixes = ['K', 'M', 'B', 'T', 'P', 'E'];
if (!value) {
return null;
}
if (Number.isNaN(value)) {
return null;
}
if (value < 1000) {
return value;
}
const exp = Math.floor(Math.log(value) / Math.log(1000));
const returnValue = (value / Math.pow(1000, exp)).toFixed(args) + suffixes[exp - 1];
return returnValue;
}
变换(9999 2)
/ /“10.00 k”
进一步改进Salman's Answer,因为它将nFormatter(33000)返回为33.0K
function nFormatter(num) {
if (num >= 1000000000) {
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
}
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
}
return num;
}
now nFormatter(33000) = 33K
推荐文章
- 如何使用Jest测试对象键和值是否相等?
- 将长模板文字行换行为多行,而无需在字符串中创建新行
- 如何在JavaScript中映射/减少/过滤一个集?
- Bower: ENOGIT Git未安装或不在PATH中
- HTML5文本区域占位符不出现
- 添加javascript选项选择
- 在Node.js中克隆对象
- 我如何捕捉Ajax查询后错误?
- 为什么在JavaScript的Date构造函数中month参数的范围从0到11 ?
- 在Windows批处理脚本中格式化日期和时间
- 使用JavaScript更改URL参数并指定默认值
- jQuery:什么是限制“数字”仅输入文本框的最佳方法?(允许使用小数点)
- 在window.setTimeout()发生之前取消/终止
- 如何删除未定义和空值从一个对象使用lodash?
- 检测当用户滚动到底部的div与jQuery