我需要显示一个货币值的格式1K等于一千,或1.1K, 1.2K, 1.9K等,如果它不是一个偶数千,否则如果低于一千,显示正常500,100,250等,使用JavaScript格式化的数字?
当前回答
我决定在这里扩展@Novellizator的答案,以满足我的需求。我想要一个灵活的函数来处理我的大部分格式化需求,而不需要外部库。
特性
选择使用顺序后缀(k, M等) 选项指定要使用的订单后缀的自定义列表 选项来约束最小和最大顺序 控制小数点后的位数 自动顺序分隔逗号 可选百分比或美元格式 控制在非数字输入的情况下返回什么 适用于负数和无穷数
例子
let x = 1234567.8;
formatNumber(x); // '1,234,568'
formatNumber(x, {useOrderSuffix: true}); // '1M'
formatNumber(x, {useOrderSuffix: true, decimals: 3, maxOrder: 1}); // '1,234.568k'
formatNumber(x, {decimals: 2, style: '$'}); // '$1,234,567.80'
x = 10.615;
formatNumber(x, {style: '%'}); // '1,062%'
formatNumber(x, {useOrderSuffix: true, decimals: 1, style: '%'}); // '1.1k%'
formatNumber(x, {useOrderSuffix: true, decimals: 5, style: '%', minOrder: 2}); // '0.00106M%'
formatNumber(-Infinity); // '-∞'
formatNumber(NaN); // ''
formatNumber(NaN, {valueIfNaN: NaN}); // NaN
函数
/*
* Return the given number as a formatted string. The default format is a plain
* integer with thousands-separator commas. The optional parameters facilitate
* other formats:
* - decimals = the number of decimals places to round to and show
* - valueIfNaN = the value to show for non-numeric input
* - style
* - '%': multiplies by 100 and appends a percent symbol
* - '$': prepends a dollar sign
* - useOrderSuffix = whether to use suffixes like k for 1,000, etc.
* - orderSuffixes = the list of suffixes to use
* - minOrder and maxOrder allow the order to be constrained. Examples:
* - minOrder = 1 means the k suffix should be used for numbers < 1,000
* - maxOrder = 1 means the k suffix should be used for numbers >= 1,000,000
*/
function formatNumber(number, {
decimals = 0,
valueIfNaN = '',
style = '',
useOrderSuffix = false,
orderSuffixes = ['', 'k', 'M', 'B', 'T'],
minOrder = 0,
maxOrder = Infinity
} = {}) {
let x = parseFloat(number);
if (isNaN(x))
return valueIfNaN;
if (style === '%')
x *= 100.0;
let order;
if (!isFinite(x) || !useOrderSuffix)
order = 0;
else if (minOrder === maxOrder)
order = minOrder;
else {
const unboundedOrder = Math.floor(Math.log10(Math.abs(x)) / 3);
order = Math.max(
0,
minOrder,
Math.min(unboundedOrder, maxOrder, orderSuffixes.length - 1)
);
}
const orderSuffix = orderSuffixes[order];
if (order !== 0)
x /= Math.pow(10, order * 3);
return (style === '$' ? '$' : '') +
x.toLocaleString(
'en-US',
{
style: 'decimal',
minimumFractionDigits: decimals,
maximumFractionDigits: decimals
}
) +
orderSuffix +
(style === '%' ? '%' : '');
}
其他回答
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 }
进一步改进@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"
一个简短的替代方案:
function nFormatter(num) { const format = [ { value: 1e18, symbol: 'E' }, { value: 1e15, symbol: 'P' }, { value: 1e12, symbol: 'T' }, { value: 1e9, symbol: 'G' }, { value: 1e6, symbol: 'M' }, { value: 1e3, symbol: 'k' }, { value: 1, symbol: '' }, ]; const formatIndex = format.findIndex((data) => num >= data.value); console.log(formatIndex) return (num / format[formatIndex === -1? 6: formatIndex].value).toFixed(2) + format[formatIndex === -1?6: formatIndex].symbol; }
进一步改进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
您可以使用模仿Python高级字符串格式化PEP3101的d3格式包:
var f = require('d3-format')
console.log(f.format('.2s')(2500)) // displays "2.5k"
推荐文章
- 如何在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: