[英]PHP format bytes translation to Javascript
不是真正的问题,而是一种挑战..
我有这个一直使用的 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];
}
测试:
function formatBytes(bytes, precision)
{
var units = ['b', 'KB', 'MB', 'GB', 'TB'];
bytes = Math.max(bytes, 0);
var pwr = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(1024));
pwr = Math.min(pwr, units.length - 1);
bytes /= Math.pow(1024, pwr);
return Math.round(bytes, precision) + ' ' + units[pwr];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.