我有柜台,有时可以得到非常大的数字,所以我需要转换数字,如:转换大的数字,以更大的因素在JavaScript
1300 => 1.3K
1000000 => 1M
等。这在JavaScript中如何实现?
我有柜台,有时可以得到非常大的数字,所以我需要转换数字,如:转换大的数字,以更大的因素在JavaScript
1300 => 1.3K
1000000 => 1M
等。这在JavaScript中如何实现?
// Truncate a number to ind decimal places
function truncNb(Nb, ind) {
var _nb = Nb * (Math.pow(10,ind));
_nb = Math.floor(_nb);
_nb = _nb/(Math.pow(10,ind));
return _nb;
}
// convert a big number to k,M,G
function int2roundKMG(val) {
var _str = "";
if (val >= 1e9) { _str = truncNb((val/1e9), 1) + ' G';
} else if (val >= 1e6) { _str = truncNb((val/1e6), 1) + ' M';
} else if (val >= 1e3) { _str = truncNb((val/1e3), 1) + ' k';
} else { _str = parseInt(val);
}
return _str;
}
伪代码:
factor = 0;
while (value > 1000) {
value = value/1000;
factor++;
}
output value (you might perhaps limit output to 3 decimal places)
convert factor to unit and output (0 = none, 1 = K, 2 = M, 3 = G...)
你可以只使用各种
function format_num(num) {
if(num < 1000)
return num;
else if(num < 1000000)
return parseInt(num/1000) + "K";
else if(num < 1000000000)
return parseInt(num/1000000) + "M";
//....
}
你一定要采取适当的四舍五入照顾的经典级联数字格式化。
我寻找的东西缩写和标签的字节大小(如1024个字节 - >“1 KB”)拾取后绑定代码一个漂亮一点,改变它只是有点,以满足您的需求(1000 - > “1 K”)。
function abbreviate_number(num) {
var sizes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
if (num < 1000) return num;
var i = parseInt(Math.floor(Math.log(num)/Math.log(1000)));
return ((i == 0) ? (num/Math.pow(1000, i)) : (num/Math.pow(1000, i)).toFixed(1)) + ' ' + sizes[i]; // use .round() in place of .toFixed if you don't want the decimal
};
仅供参考,这里是我需要的。
function format_bytes(bytes) {
var sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
if (bytes == 0) return '';
if (bytes == 1) return '1 Byte';
var i = parseInt(Math.floor(Math.log(bytes)/Math.log(1024)));
return ((i == 0)? (bytes/Math.pow(1024, i)) : (bytes/Math.pow(1024, i)).toFixed(1)) + ' ' + sizes[i];
};
我想出这些答案的时候晚了,我一直在寻找一个干净的方式做,但为了以防万一,如果有人一直在寻找复制粘贴的角度滤波器这样做,这里是我的。相同的逻辑,上述答复:)
只是为了确定为0
返回1k
HTML:
<div ng-repeat="d in data>
<div class="numbers">{{d | KGMPformat}}</div>
</div>
JS:
// controller:
$scope.data = [123,12345,1234567,12345678,12345678901]
// filter:
(function(app) {
app.filter('KGMPformat', function() {
return function(value) {
if (value<1e3) return value;
if (value<1e6) return (value - value%1e3)/1e3 + "K";
if (value<1e9) return (value - value%1e6)/1e6 + "G";
if (value<1e12) return (value - value%1e9)/1e9 + "M";
if (value<1e15) return (value - value%1e12)/1e12 + "P";
return value;
};
});
})(myApp);
注意'GMk'都够32位值,对于64位,你需要'EPTGMk'。 – schnaader 2011-03-11 16:18:05
@schnaader:你是对的,很容易添加更多的乘数,留作练习。 – Toto 2011-03-11 16:27:30