不是真正的问题,而是一种挑战..
我有这个我一直使用的 PHP 函数,现在我需要它在 Javascript 中。
function formatBytes($bytes, $precision = 0) {
$units = array('b', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
编辑:多亏了回复,我想出了一些更短但不精确的东西(如果你有一些想法,请告诉我)
function format_bytes(size){
var base = Math.log(size) / Math.log(1024);
var suffixes = ['b', 'KB', 'MB', 'GB', 'TB' , 'PB' , 'EB'];
return Math.round(Math.pow(1024, base - Math.floor(base)), 0) + ' ' + suffixes[Math.floor(base)];
}
最佳答案
觉得这个是对的,没测试过:
更新:必须修复它,因为没有默认的精度,而且我在最后一行有错字,现在可以正常使用了。
function formatBytes(bytes, precision) {
var units = ['b', 'KB', 'MB', 'GB', 'TB'];
var bytes = Math.max(bytes, 0);
var pow = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(1024));
pow = Math.min(pow, units.length - 1);
bytes = bytes / Math.pow(1024, pow);
precision = (typeof(precision) == 'number' ? precision : 0);
return (Math.round(bytes * Math.pow(10, precision)) / Math.pow(10, precision)) + ' ' + units[pow];
}
关于javascript - PHP 格式字节转换为 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4258025/