Pregunta

Tengo datos en bytes. Necesito dibujar estos valores como etiquetas legibles por humanos en un gráfico (como 2,5 kb, 14MB etc.) y necesidad de ayuda con la función (datos de entrada - valor real, la salida - cadena legible por humanos).

Lo hice funcion de este tipo, pero quiero más elegante realización

function tickFormatter(value, type) {

    var suffix = (type == "bytes") ? ['B', 'KB', 'MB', 'GB'] : ['', 'K', 'M', 'G']

    if(value > (1024 * 1024 * 1024 * 1024)) {
        return (value / (1024 * 1024 * 1024 * 1024)).toFixed(2) + suffix[3]
    } else if(value > (1024 * 1024 * 1024)) {
        return (value / (1024 * 1024 * 1024)).toFixed(2) + suffix[2]
    } else if (value > (1024 * 1024)) {
        return (value / (1024 * 1024)).toFixed(2) + suffix[1]
    } else {
        return value.toFixed(2) + suffix[0]
    }
}
¿Fue útil?

Solución

Me encanta esta aplicación: clara y compacta:

function readablizeBytes(bytes) {
    var s = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];
    var e = Math.floor(Math.log(bytes) / Math.log(1024));
    return (bytes / Math.pow(1024, e)).toFixed(2) + " " + s[e];
}

Uso:

readablizeBytes(10000000)
"9.54 MB"

Yo no tomar el crédito de este.

Otros consejos

Esto es lo que yo uso. Se redondea a la unidad más cercana, por lo que 1000 es "0.98KB" Si usted no quiere que, a continuación, cambiar el primer Math.round a un piso.

var SizePrefixes = ' KMGTPEZYXWVU';
function GetHumanSize(size) {
  if(size <= 0) return '0';
  var t2 = Math.min(Math.round(Math.log(size)/Math.log(1024)), 12);
  return (Math.round(size * 100 / Math.pow(1024, t2)) / 100) +
    SizePrefixes.charAt(t2).replace(' ', '') + 'B';
}

Tal vez algo como esto?

function readable (nb_bytes) {
    if (nb_bytes < 1024) return nb_bytes + 'B';
    else if (nb_bytes < 1024 * 1024) return (Math.round((nb_bytes / 1024) * 100) / 100) + 'KB';
    else return (Math.round((nb_bytes / 1024 / 1024) * 100) / 100) + 'MB';
}

[EDIT]

Muy bien, ya que desea algo más elegante, que supongo que usted está pensando en un bucle. Tal vez esto se adapte a sus necesidades:

function readable (nb_bytes,type) {
    var suffix = type ? ['B','KB','MB','GB'] : ['','K','M','G'];
    var i = 0;
    while (nb_bytes > 1024 && i < suffix.length - 1) {
        ++i;
        nb_bytes = Math.round((nb_bytes / 1024) * 100) / 100;
    }
    return (nb_bytes) + suffix[i];
}

Aquí supone type era un valor lógico - el cambio a lo que más le convenga

.

Versión modificada de Amer:

(function GetHumanSize(size) {
  var SizePrefixes = ['','K','M','G','T','P','E','Z','Y'];
  if(size <= 0) return '0';
  var t2 = Math.min(Math.round(Math.log(size)/Math.log(1024)),
                    SizePrefixes.length-1);
  return String((Math.round(size * 100 / Math.pow(1024, t2)) / 100)) + 
         ' ' + SizePrefixes[t2] + 'iB';
})(Math.pow(2,131)) === "2251799813685248 YiB"

Con:

  • IEC sufijos
  • No hay sufijos no estándar
function formatSize(size, standard) {
    if (standard) { 
        standard = standard.toLowerCase();
    }

    var n = 0, 
        base = standard == 'si' ? 1000 : 1024, 
        prefixes = ' KMGTPEZY';

    if (size < 1) {
        return 0;
    }
    else if (size >= base) {
        n = Math.floor( Math.log(size) / Math.log(base) );

        if (n >= prefixes.length) {
            return 'N/A';
        }

        size = ( size / Math.pow(base, n) ).toFixed(2) * 1 + ' ';
    }

    return size + prefixes[n] + ( n && standard == 'iec' ? 'i' : '' ) + 'B';
}

Prueba:

for (var i = 0; i++ < 10;) console.log( formatSize( Math.pow(10, i) ) ); 

Salida:

10 B
100 B
1000 B
9.77 KB
97.66 KB
976.56 KB
9.54 MB
95.37 MB
953.67 MB
9.31 GB

Tomé lo que sentía el mejor de los dos mejores soluciones y se acercó con esto, es más rápido que el primero, más lento que el segundo. Pero su propósito es tener siempre exactamente 3 caracteres, y no redondos. La razón para el límite de 3 caracteres era debido a las limitaciones de tamaño para el contenedor que estaba siendo colocado en. Además en caso de que desee utilizarlo para dar formato a base de 2 números no todo lo que necesita hacer es cambiar el kilo de 1000. También cortocircuitos si el número es menor de 1 k

var kilo = 1024, suffix = ' KMGTPEZYXWVU', humanReadable = function (number) {
  var retValue = false;
  if (typeof number == "number") {
      if (number < kilo) {
          retValue = number.toString();
      } else {
          var e = Math.floor(Math.log(number) / Math.log(kilo));
          retValue = Number((number / Math.pow(kilo, e)).toString().slice(0, 3)) + suffix.charAt(e) + 'B';
      }
  }
  return retValue;
};

respuestas realmente me ayudó, así que decidí escribir un método de utilidad que resuelve este problema del tamaño de formatear una vez por todas.

Vea mis JSutils Repo página wiki: https://bitbucket.org/AAverin/jsutils/ | https://github.com/AAverin/JSUtils Tiene humanReadeableSize método que usa modo de redondeo el tamaño de Amir, sino que también soporta la conversión entre la base habitual de 2 (KIB, MIB) y la base de 10 números (KB, MB).

Se puede redondear hacia abajo al valor más cercano, sino también a todo el año en caso de que desee, por ejemplo, obtener la cantidad de KB están en PB.

No dude en para agarrarlo y su uso en sus proyectos!

Se podía utilizar number_to_human_size (número, opciones = {})

number_to_human_size(1234567)

ejemplos:

number_to_human_size(123)                                          # => 123 Bytes
number_to_human_size(1234)                                         # => 1.21 KB
number_to_human_size(12345)                                        # => 12.1 KB
number_to_human_size(1234567)                                      # => 1.18 MB
number_to_human_size(1234567890)                                   # => 1.15 GB
number_to_human_size(1234567890123)                                # => 1.12 TB
number_to_human_size(1234567, precision: 2)                        # => 1.2 MB
number_to_human_size(483989, precision: 2)                         # => 470 KB
number_to_human_size(1234567, precision: 2, separator: ',')        # => 1,2 MB

http: //api.rubyonrails .org / clases / ActionView / Ayudantes / NumberHelper.html # método-i-number_to_human_size

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top