Domanda

Non ho dati in byte. Ho bisogno di disegnare questi valori come etichette leggibili su un grafico (come 2.5KB, 14MB etc.) e necessità di aiuto con la funzione (dati di input - valore effettivo, uscita - stringa leggibile).

Ho fatto funcion come questo, ma voglio realizzazione più elegante

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]
    }
}
È stato utile?

Soluzione

Amo questa implementazione: chiara e compatta:

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];
}

Utilizzo:

readablizeBytes(10000000)
"9.54 MB"

Non prendere il merito di questo.

Altri suggerimenti

Questo è quello che uso. Si arrotonda all'unità più vicina, quindi 1000 è "0.98KB" Se non si desidera che, quindi modificare il primo Math.round ad un pavimento.

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';
}

Forse qualcosa di simile?

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]

Va bene, dal momento che si desidera qualcosa di più elegante, ti assumere stai pensando di un ciclo. Forse questo soddisfa le tue esigenze:

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];
}

Qui ho assunto type era un valore booleano - cambiamento a tutto ciò che più vi si addice meglio

.

Versione modificata di Amer di:

(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 suffissi
  • Non ci sono suffissi non standard
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';
}

Prova:

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

Output:

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

ho preso quello che ho sentito il meglio dei primi due soluzioni e si avvicinò con questo, il suo più veloce rispetto alla prima, più lento del secondo. Ma il suo scopo è quello di avere sempre esattamente 3 caratteri, e non rotonda. La ragione per il limite di 3 caratteri è causa di vincoli di dimensione per il contenitore veniva posta in. Inoltre si dovrebbe desiderare di usarlo per formattare non base di 2 numeri tutto quello che dovete fare è cambiare chilo al 1000. Ha inoltre cortocircuito se il numero è sotto 1k

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;
};

Le risposte mi ha veramente aiutato, così ho deciso di scrivere un metodo di utilità che risolve questo problema di dimensione formattazione una volta per tutte.

Verifichi i miei JSutils Repo pagina wiki: https://bitbucket.org/AAverin/jsutils/ | https://github.com/AAverin/JSUtils Ha humanReadeableSize metodo che utilizza modo di arrotondamento della dimensione di Amir, ma supporta anche la conversione tra il consueto base 2 (KiB, MiB) e base 10 numeri (KB, MB).

Si può arrotondare fino al valore più vicino, ma anche fino turno nel caso in cui si desidera, ad esempio, ottenere quanto KB sono in PB.

Non esitate a afferrarlo e utilizzare nei vostri progetti!

Potrebbe utilizzare number_to_human_size (numero, opzioni = {})

number_to_human_size(1234567)

Esempi:

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

come nella documentazione http: //api.rubyonrails .org / classes / ActionView / Helpers / NumberHelper.html # metodo-i-number_to_human_size

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top