PHP格式字节到Javascript的转换

PHP格式字节到Javascript的转换,javascript,php,format,Javascript,Php,Format,这不是一个真正的问题,而是一种挑战 我有这个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(

这不是一个真正的问题,而是一种挑战

我有这个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 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];
}

@John Giotta为这个错误道歉,我忘了为precision.Math.round(number,precision)设置默认值,我知道它是存在的,但是我没有使用“precision”参数,因为它上面的Javascript规范的大多数定义似乎都没有指示precision参数的可用性,所以我的速度变慢了。所以我用放大然后除法来实现它。精度对我来说不适用于Math.round(字节,精度)。请改为尝试bytes.toFixed(精度)。
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];
}