我有櫃檯,有時可以得到非常大的數字,所以我需要轉換數字,如:轉換大的數字,以更大的因素在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