我需要显示一个货币值的格式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)}`); }); });
其他回答
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”
进一步改进@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"
这里有一个简单的解决方案,可以避免所有的if语句(借助Math的力量)。
var SI_SYMBOL = ["", "k", "M", "G", "T", "P", "E"];
function abbreviateNumber(number){
// what tier? (determines SI symbol)
var tier = Math.log10(Math.abs(number)) / 3 | 0;
// if zero, we don't need a suffix
if(tier == 0) return number;
// get suffix and determine scale
var suffix = SI_SYMBOL[tier];
var scale = Math.pow(10, tier * 3);
// scale the number
var scaled = number / scale;
// format number and add suffix
return scaled.toFixed(1) + suffix;
}
奖金模因
SI代表什么?
这是非常优雅的。
function formatToUnits(number, precision) {
const abbrev = ['', 'k', 'm', 'b', 't'];
const unrangifiedOrder = Math.floor(Math.log10(Math.abs(number)) / 3)
const order = Math.max(0, Math.min(unrangifiedOrder, abbrev.length -1 ))
const suffix = abbrev[order];
return (number / Math.pow(10, order * 3)).toFixed(precision) + suffix;
}
formatToUnits(12345, 2)
==> "12.35k"
formatToUnits(0, 3)
==> "0.000"
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 }
推荐文章
- 如何在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: