我需要显示一个货币值的格式1K等于一千,或1.1K, 1.2K, 1.9K等,如果它不是一个偶数千,否则如果低于一千,显示正常500,100,250等,使用JavaScript格式化的数字?
当前回答
简单通用的方法
可以将COUNT_FORMATS配置对象设置为您想要的长度或长度,这取决于您测试的值范围。
// Configuration const COUNT_FORMATS = [ { // 0 - 999 letter: '', limit: 1e3 }, { // 1,000 - 999,999 letter: 'K', limit: 1e6 }, { // 1,000,000 - 999,999,999 letter: 'M', limit: 1e9 }, { // 1,000,000,000 - 999,999,999,999 letter: 'B', limit: 1e12 }, { // 1,000,000,000,000 - 999,999,999,999,999 letter: 'T', limit: 1e15 } ]; // Format Method: function formatCount(value) { const format = COUNT_FORMATS.find(format => (value < format.limit)); value = (1000 * value / format.limit); value = Math.round(value * 10) / 10; // keep one decimal number, only if needed return (value + format.letter); } // Test: const test = [274, 1683, 56512, 523491, 9523489, 5729532709, 9421032489032]; test.forEach(value => console.log(`${ value } >>> ${ formatCount(value) }`));
其他回答
韦伦·弗林解决方案的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)}`); }); });
/*including negative values*/
function nFormatter(num) {
let neg = false;
if(num < 0){
num = num * -1;
neg = true;
}
if (num >= 1000000000) {
if(neg){
return -1 * (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
}
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
}
if (num >= 1000000) {
if(neg){
return -1 * (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
}
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
}
if (num >= 1000) {
if(neg){
return -1 * (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
}
return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
}
return num;
}
我认为这是一个解决方案。
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);
Waylon flynn的答案的修改版本,支持负指数:
function metric(number) { const SI_SYMBOL = [ ["", "k", "M", "G", "T", "P", "E"], // + ["", "m", "μ", "n", "p", "f", "a"] // - ]; const tier = Math.floor(Math.log10(Math.abs(number)) / 3) | 0; const n = tier < 0 ? 1 : 0; const t = Math.abs(tier); const scale = Math.pow(10, tier * 3); return { number: number, symbol: SI_SYMBOL[n][t], scale: scale, scaled: number / scale } } function metric_suffix(number, precision) { const m = metric(number); return (typeof precision === 'number' ? m.scaled.toFixed(precision) : m.scaled) + m.symbol; } for (var i = 1e-6, s = 1; i < 1e7; i *= 10, s *= -1) { // toggles sign in each iteration console.log(metric_suffix(s * (i + i / 5), 1)); } console.log(metric(0));
预期的输出:
1.2μ
-12.0μ
120.0μ
-1.2m
12.0m
-120.0m
1.2
-12.0
120.0
-1.2k
12.0k
-120.0k
1.2M
{ number: 0, symbol: '', scale: 1, scaled: 0 }
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”
推荐文章
- 如何使用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