javascript - PHP 格式字节转换为 Javascript

标签 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($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/

相关文章:

html - 页脚格式问题,可能是 CSS 问题?

javascript - ES 6 + 用于基于 Object Prop 引用数组中特定对象的语法糖

javascript - ng-include 被调用的太频繁了

Javascript - 无法显示 UL,而是获取 [object HTMLUListElement]

php - 应该将什么传递给 if() 以打印 'Hello World' ?

php - 选择使用 Zend DB 连接两个表

format - NLog:使用空格格式化日志级别

javascript - 从 Javascript 调用网络服务

php - 如何打印 Error 405 Method not allowed to users

jquery - 从 API 检索完整日期并随后进行格式化