我需要显示一个货币值的格式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"
其他回答
听起来这应该对你有用:
函数 kFormatter(num) { 返回 Math.abs(num) > 999 ?Math.sign(num)*((Math.abs(num)/1000).toFixed(1)) + 'k' : Math.sign(num)*Math.abs(num) } console.log(kFormatter(1200));1.2k console.log(kFormatter(-1200));-1.2k console.log(kFormatter(900));900 console.log(kFormatter(-900));-900
一个更普遍的版本:
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)); });
我用的是这个函数。它适用于php和javascript。
/**
* @param $n
* @return string
* Use to convert large positive numbers in to short form like 1K+, 100K+, 199K+, 1M+, 10M+, 1B+ etc
*/
function num_format($n) {
$n_format = null;
$suffix = null;
if ($n > 0 && $n < 1000) {
$n_format = Math.floor($n);
$suffix = '';
}
else if ($n == 1000) {
$n_format = Math.floor($n / 1000); //For PHP only use floor function insted of Math.floor()
$suffix = 'K';
}
else if ($n > 1000 && $n < 1000000) {
$n_format = Math.floor($n / 1000);
$suffix = 'K+';
} else if ($n == 1000000) {
$n_format = Math.floor($n / 1000000);
$suffix = 'M';
} else if ($n > 1000000 && $n < 1000000000) {
$n_format = Math.floor($n / 1000000);
$suffix = 'M+';
} else if ($n == 1000000000) {
$n_format = Math.floor($n / 1000000000);
$suffix = 'B';
} else if ($n > 1000000000 && $n < 1000000000000) {
$n_format = Math.floor($n / 1000000000);
$suffix = 'B+';
} else if ($n == 1000000000000) {
$n_format = Math.floor($n / 1000000000000);
$suffix = 'T';
} else if ($n >= 1000000000000) {
$n_format = Math.floor($n / 1000000000000);
$suffix = 'T+';
}
/***** For PHP ******/
// return !empty($n_format . $suffix) ? $n_format . $suffix : 0;
/***** For Javascript ******/
return ($n_format + $suffix).length > 0 ? $n_format + $suffix : 0;
}
如果你喜欢,就把功劳归于韦伦·弗林
这比他处理负数和“。0”的情况。
循环和“如果”情况越少,IMO就越好。
function abbreviateNumber(number) {
const SI_POSTFIXES = ["", "k", "M", "G", "T", "P", "E"];
const sign = number < 0 ? '-1' : '';
const absNumber = Math.abs(number);
const tier = Math.log10(absNumber) / 3 | 0;
// if zero, we don't need a prefix
if(tier == 0) return `${absNumber}`;
// get postfix and determine scale
const postfix = SI_POSTFIXES[tier];
const scale = Math.pow(10, tier * 3);
// scale the number
const scaled = absNumber / scale;
const floored = Math.floor(scaled * 10) / 10;
// format number and add postfix as suffix
let str = floored.toFixed(1);
// remove '.0' case
str = (/\.0$/.test(str)) ? str.substr(0, str.length - 2) : str;
return `${sign}${str}${postfix}`;
}
jsFiddle测试用例-> https://jsfiddle.net/qhbrz04o/9/
最简单最简单的方法是
new Intl.NumberFormat('en-IN', {
notation: "compact",
compactDisplay: "short",
style: 'currency',
currency: 'INR'
}).format(1000).replace("T", "K")
这对任何数字都适用。包括L、Cr等。
注意:不能在safari中工作。
推荐文章
- 如何在禁用按钮上启用引导工具提示?
- 使用JQuery阻止表单提交
- jQuery发布JSON
- Node.js全局变量
- 在前一个函数完成后调用另一个函数
- JavaScript中两个日期之间的月份差异
- 如何同时运行两个jQuery动画?
- 如何将FormData (HTML5对象)转换为JSON
- Object.hasOwnProperty()产生ESLint 'no-prototype-builtins'错误:如何修复?
- 如何将Node.js流的内容读入字符串变量?
- 两个感叹号?
- jQuery ' .is(":visible") '在Chrome中无效
- 如何在JavaScript中计算今天之前三个月的日期?
- 在Go中int类型的最大值
- <script defer="defer">到底是如何工作的?