Formatting the amount / amount of data as a string

A common task in many programs is to convert the number of bytes (for example, from disk capacity or file size) to a more human-readable form. Consider 150000000000 bytes as more readable as "150 GB" or "139.7 GB".

Are there libraries that contain functionality to perform these transformations? In python? In c? In pseudo code? Are there any best practices regarding the “most readable” form, for example, the number of significant characters, precision, etc.?

+3
source share
3 answers

, :

from math import log

byteunits = ('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')

def filesizeformat(value):
    exponent = int(log(value, 1024))
    return "%.1f %s" % (float(value) / pow(1024, exponent), byteunits[exponent])
+7

, , . :

  • base-1000 base-1024?
  • ?

, . -, , , . -, , . , Windows, base-1024, , Windows. , base-1024, RAM. , base-1000, .

, , . , , , - , .

+1

Well, I usually go for this:

<?php
$factor = 0;
$units = ['B','KiB','MiB','GiB','TiB']
while( $size > 1024 && $factor<count($units-1)) {
    $factor++;
    $size /= 1024; // or $size >>= 10;
}
echo round($size,2).$units[$factor];
?>

Hope this helps!

0
source

Source: https://habr.com/ru/post/1774856/


All Articles