我需要显示一个货币值的格式1K等于一千,或1.1K, 1.2K, 1.9K等,如果它不是一个偶数千,否则如果低于一千,显示正常500,100,250等,使用JavaScript格式化的数字?
当前回答
这是非常优雅的。
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"
其他回答
/*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;
}
一个更普遍的版本:
function nFormatter(num, digits) { const lookup = [ { 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" } ]; const rx = /\.0+$|(\.[0-9]*[1-9])0+$/; var item = lookup.slice().reverse().find(function(item) { return num >= item.value; }); return item ? (num / item.value).toFixed(digits).replace(rx, "$1") + item.symbol : "0"; } /* * Tests */ const tests = [ { num: 0, digits: 1 }, { num: 12, digits: 1 }, { 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 } ]; tests.forEach(function(test) { console.log("nFormatter(" + test.num + ", " + test.digits + ") = " + nFormatter(test.num, test.digits)); });
以下是我对韦伦·弗林的回答的看法。这将删除.0并修复当层不是整数时的未定义。
const SI_SYMBOL = ['', 'k', 'M', 'G', 'T', 'P', 'E'];
abbreviateNumber(num) {
const tier = Math.floor(Math.log10(num) / 3) || 0;
let result = '' + num;
// if zero, we don't need a suffix
if (tier > 0) {
// get suffix and determine scale
const suffix = SI_SYMBOL[tier];
const scale = Math.pow(10, tier * 3);
// scale the number
const scaled = num / scale;
// format number and add suffix
result = scaled.toFixed(1).replace('.0', '') + suffix;
}
return result;
}
我决定在这里扩展@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 === '%' ? '%' : '');
}
function AmountConveter(amount) {
return Math.abs(amount) > 999
? Math.sign(amount) * (Math.abs(amount) / 1000).toFixed(1) + "k"
: Math.sign(amount) * Math.abs(amount);
}
console.log(AmountConveter(1200)); // 1.2k
console.log(AmountConveter(-1200)); // -1.2k
console.log(AmountConveter(900)); // 900
console.log(AmountConveter(-900)); // -900
推荐文章
- 如何使用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