本文介绍了使用像1.5K,1M,1G等度量标准前缀格式化javascript数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用来显示数字,其中包含3位有效数字,例如: p>
1显示为1
999显示为999
1000显示为1K
999000显示为999K
1000000显示为1M
1500000显示为1.5M
1000000000显示为1G
等...
我可以编写自己的javascript函数来做到这一点,但我想知道是否有一个像这样的格式化数字的标准方式?
<$ p $ p>
var ranges = [
{divider:1e18,后缀:'P'},
{divider:1e15,后缀:'E'},
{divider :1e12,后缀:'T'},
{divider:1e9,后缀:'G'},
{divider:1e6,后缀:'M'},
{divider:1e3 ,后缀:'k'}
];
函数formatNumber(n){
for(var i = 0; i< ranges.length; i ++){
if(n> = ranges [i] divider){
return(n / ranges [i] .divider).toString()+ ranges [i] .suffix;
}
return n.toString();
code
用法示例:
var s = formatNumber(999000);
要处理负数,您可以在函数中加入:
$ b $
if(n return' - '+ formatNumber(-n);
}
I want to display numbers using a Metric Prefix with 3 significant digits like so:
1 shows as 1
999 shows as 999
1000 shows as 1K
999000 shows as 999K
1000000 shows as 1M
1500000 shows as 1.5M
1000000000 shows as 1G
etc...
I could write my own javascript function to do this but I was wondering if there is a standard way of formatting numbers like this?
解决方案 You can put the ranges in an array of objects, and just loop through it to format the number:
var ranges = [
{ divider: 1e18 , suffix: 'P' },
{ divider: 1e15 , suffix: 'E' },
{ divider: 1e12 , suffix: 'T' },
{ divider: 1e9 , suffix: 'G' },
{ divider: 1e6 , suffix: 'M' },
{ divider: 1e3 , suffix: 'k' }
];
function formatNumber(n) {
for (var i = 0; i < ranges.length; i++) {
if (n >= ranges[i].divider) {
return (n / ranges[i].divider).toString() + ranges[i].suffix;
}
}
return n.toString();
}
Usage example:
var s = formatNumber(999000);
To also handle negative numbers, you would add this first in the function:
if (n < 0) {
return '-' + formatNumber(-n);
}
这篇关于使用像1.5K,1M,1G等度量标准前缀格式化javascript数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-08 05:15