我有反击,有时它可以获得非常大的数字,所以我需要转换数字,如:
1300 => 1.3K
1000000 => 1M
等等。这在JavaScript中如何实现?
答案 0 :(得分:4)
// 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;
}
答案 1 :(得分:1)
我在寻找缩写和标记字节大小(例如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];
};
答案 2 :(得分:0)
伪代码:
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...)
答案 3 :(得分:0)
你可以使用经典的级联数字格式化程序
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";
//....
}
你只需要适当地处理四舍五入。
答案 4 :(得分:0)
当我正在寻找一种干净的方式来做这件事时,我得出了这些答案,但以防万一有人在寻找粘贴角度过滤器的副本,这就是我的。与上述响应相同的逻辑:)
只是为了确保001234
返回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);