我需要显示一个货币值的格式1K等于一千,或1.1K, 1.2K, 1.9K等,如果它不是一个偶数千,否则如果低于一千,显示正常500,100,250等,使用JavaScript格式化的数字?
当前回答
下面是一个使用for的选项:
函数numberFormat(d) For (var e = 0;D >= 1000;e + +) { D /= 1000; } return d.toFixed(3) + [", ' k', ' M', ' G'][e]; } let s = numberFormat(9012345678); console.log(s == '9.012 G');
其他回答
/**
* Shorten number to thousands, millions, billions, etc.
* http://en.wikipedia.org/wiki/Metric_prefix
*
* @param {number} num Number to shorten.
* @param {number} [digits=0] The number of digits to appear after the decimal point.
* @returns {string|number}
*
* @example
* // returns '12.5k'
* shortenLargeNumber(12543, 1)
*
* @example
* // returns '-13k'
* shortenLargeNumber(-12567)
*
* @example
* // returns '51M'
* shortenLargeNumber(51000000)
*
* @example
* // returns 651
* shortenLargeNumber(651)
*
* @example
* // returns 0.12345
* shortenLargeNumber(0.12345)
*/
function shortenLargeNumber(num, digits) {
var units = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'],
decimal;
for(var i=units.length-1; i>=0; i--) {
decimal = Math.pow(1000, i+1);
if(num <= -decimal || num >= decimal) {
return +(num / decimal).toFixed(digits) + units[i];
}
}
return num;
}
谢谢@Cos的评论,我删除了Math。round10依赖。
您可以使用模仿Python高级字符串格式化PEP3101的d3格式包:
var f = require('d3-format')
console.log(f.format('.2s')(2500)) // displays "2.5k"
韦伦·弗林解决方案的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)}`); }); });
最简单最简单的方法是
new Intl.NumberFormat('en-IN', {
notation: "compact",
compactDisplay: "short",
style: 'currency',
currency: 'INR'
}).format(1000).replace("T", "K")
这对任何数字都适用。包括L、Cr等。
注意:不能在safari中工作。
支持负数 检查!isFinite 如果你想要最大单位是M,将' K M G T P E Z Y'改为' K M' 基数选项(1K = 1000 / 1K = 1024)
Number.prototype.prefix = function (precision, base) { var units = ' K M G T P E Z Y'.split(' '); if (typeof precision === 'undefined') { precision = 2; } if (typeof base === 'undefined') { base = 1000; } if (this == 0 || !isFinite(this)) { return this.toFixed(precision) + units[0]; } var power = Math.floor(Math.log(Math.abs(this)) / Math.log(base)); // Make sure not larger than max prefix power = Math.min(power, units.length - 1); return (this / Math.pow(base, power)).toFixed(precision) + units[power]; }; console.log('0 = ' + (0).prefix()) // 0.00 console.log('10000 = ' + (10000).prefix()) // 10.00K console.log('1234000 = ' + (1234000).prefix(1)) // 1.2M console.log('-10000 = ' + (-10240).prefix(1, 1024)) // -10.0K console.log('-Infinity = ' + (-Infinity).prefix()) // -Infinity console.log('NaN = ' + (NaN).prefix()) // NaN
推荐文章
- 如何在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: