Python Format Size Application (Converting B to Kb, Mb, Gb, Tb)

Better way to convert file sizes in Python [closed]

There is hurry.filesize that will take the size in bytes and make a nice string out if it.

>>> from hurry.filesize import size
>>> size(11000)
'10K'
>>> size(198283722)
'189M'

Or if you want 1K == 1000 (which is what most users assume):

>>> from hurry.filesize import size, si
>>> size(11000, system=si)
'11K'
>>> size(198283722, system=si)
'198M'

It has IEC support as well (but that wasn't documented):

>>> from hurry.filesize import size, iec
>>> size(11000, system=iec)
'10Ki'
>>> size(198283722, system=iec)
'189Mi'

Because it's written by the Awesome Martijn Faassen, the code is small, clear and extensible. Writing your own systems is dead easy.

Here is one:

mysystem = [
(1024 ** 5, ' Megamanys'),
(1024 ** 4, ' Lotses'),
(1024 ** 3, ' Tons'),
(1024 ** 2, ' Heaps'),
(1024 ** 1, ' Bunches'),
(1024 ** 0, ' Thingies'),
]

Used like so:

>>> from hurry.filesize import size
>>> size(11000, system=mysystem)
'10 Bunches'
>>> size(198283722, system=mysystem)
'189 Heaps'

Format bytes to kilobytes, megabytes, gigabytes

function formatBytes($bytes, $precision = 2) { 
$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);

// Uncomment one of the following alternatives
// $bytes /= pow(1024, $pow);
// $bytes /= (1 << (10 * $pow));

return round($bytes, $precision) . ' ' . $units[$pow];
}

(Taken from php.net, there are many other examples there, but I like this one best :-)

Converting KB to MB, GB, TB dynamically

You are performing integer division. So the result of division is also integer. And fractional part is truncated.

so, 1245 / 1024 = 1

Change your division to floating point division: -

double m = size/1024.0;
double g = size/1048576.0;
double t = size/1073741824.0;

Also, your comparison is faulty. You should do the comparison with 1.

if (m > 1), if (t > 1), if (g > 1)

Ideally I would change your comparison to: -

    if (t > 1) {
hrSize = dec.format(t).concat("TB");
} else if (g > 1) {
hrSize = dec.format(g).concat("GB");
} else if (m > 1) {
hrSize = dec.format(m).concat("MB");
} else {
hrSize = dec.format(size).concat("KB");
}

You need to compare with the higher unit first, and then move to the lower one.

PHP convert KB MB GB TB etc to Bytes

Here's a function to achieve this:

function convertToBytes(string $from): ?int {
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$number = substr($from, 0, -2);
$suffix = strtoupper(substr($from,-2));

//B or no suffix
if(is_numeric(substr($suffix, 0, 1))) {
return preg_replace('/[^\d]/', '', $from);
}

$exponent = array_flip($units)[$suffix] ?? null;
if($exponent === null) {
return null;
}

return $number * (1024 ** $exponent);
}

$testCases = ["13", "13B", "13KB", "10.5KB", "123Mi"];
var_dump(array_map('convertToBytes', $testCases));

Output:

array(5) { [0]=> int(13) [1]=> int(13) [2]=> int(13312) [3]=>
int(10752) [4]=> NULL } int(1)

How to convert MB to GB with precision in Python

Given:

>>> sizes = ['999.992 MB', '2.488 GB', '401 KB']

First agree on what 'precision' means. Since your input is a float, it is a fair assumption that 'precision' is limited to the input precision.

To calculate, first convert to base bytes (know though that your actual precision is no better than the input precision):

>>> defs={'KB':1024, 'MB':1024**2, 'GB':1024**3, 'TB':1024**4} 
>>> bytes=[float(lh)*defs[rh] for lh, rh in [e.split() for e in sizes]]
>>> bytes
[1048567611.392, 2671469658.112, 410624.0]

Then convert to magnitude desired:

>>> sd='GB'
>>> ['{:0.2} {}'.format(e/defs[sd], sd) for e in bytes]
['0.98 GB', '2.5 GB', '0.00038 GB']
>>> sd='MB'
>>> ['{:0.2} {}'.format(e/defs[sd], sd) for e in bytes]
['1e+03 MB', '2.5e+03 MB', '0.39 MB']
>>> sd='TB'
>>> ['{:0.2} {}'.format(e/defs[sd], sd) for e in bytes]
['0.00095 TB', '0.0024 TB', '3.7e-07 TB']

Correct way to convert size in bytes to KB, MB, GB in JavaScript

From this: (source)

function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}

Note: This is original code, Please use fixed version below.


Fixed version, unminified and ES6'ed: (by community)

function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';

const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

const i = Math.floor(Math.log(bytes) / Math.log(k));

return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

Fixed Version (by StackOverflow's community, minified by JSCompress)

function formatBytes(a,b=2,k=1024){with(Math){let d=floor(log(a)/log(k));return 0==a?"0 Bytes":parseFloat((a/pow(k,d)).toFixed(max(0,b)))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][d]}}

Usage :

// formatBytes(bytes,decimals)

formatBytes(1024); // 1 KB
formatBytes('1024'); // 1 KB
formatBytes(1234); // 1.21 KB
formatBytes(1234, 3); // 1.205 KB

Demo / source :

function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';

const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

const i = Math.floor(Math.log(bytes) / Math.log(k));

return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

// ** Demo code **
var p = document.querySelector('p'),
input = document.querySelector('input');

function setText(v){
p.innerHTML = formatBytes(v);
}
// bind 'input' event
input.addEventListener('input', function(){
setText( this.value )
})
// set initial text
setText(input.value);
<input type="text" value="1000">
<p></p>

Convert size notation with units (100kb, 32MB) to number of bytes in Python

I liked the simple approach taken by @Robson, but I noticed it has a number of corner cases that it didn't handle. The version below is largely the same, but it adds/fixes the following:

  • Adds support for byte, kilobyte, etc.
  • Provides support for singular units, e.g., "1 byte"
  • Adds support for yottabytes, zetabytes, etc. The version above would crash for these.
  • Adds support for spaces before, after, and in the input.
  • Adds support for floats ("5.2 mb")
  • Bigger docstring

Here's the code:

def convert_size_to_bytes(size_str):
"""Convert human filesizes to bytes.

Special cases:
- singular units, e.g., "1 byte"
- byte vs b
- yottabytes, zetabytes, etc.
- with & without spaces between & around units.
- floats ("5.2 mb")

To reverse this, see hurry.filesize or the Django filesizeformat template
filter.

:param size_str: A human-readable string representing a file size, e.g.,
"22 megabytes".
:return: The number of bytes represented by the string.
"""
multipliers = {
'kilobyte': 1024,
'megabyte': 1024 ** 2,
'gigabyte': 1024 ** 3,
'terabyte': 1024 ** 4,
'petabyte': 1024 ** 5,
'exabyte': 1024 ** 6,
'zetabyte': 1024 ** 7,
'yottabyte': 1024 ** 8,
'kb': 1024,
'mb': 1024**2,
'gb': 1024**3,
'tb': 1024**4,
'pb': 1024**5,
'eb': 1024**6,
'zb': 1024**7,
'yb': 1024**8,
}

for suffix in multipliers:
size_str = size_str.lower().strip().strip('s')
if size_str.lower().endswith(suffix):
return int(float(size_str[0:-len(suffix)]) * multipliers[suffix])
else:
if size_str.endswith('b'):
size_str = size_str[0:-1]
elif size_str.endswith('byte'):
size_str = size_str[0:-4]
return int(size_str)

And I wrote a bunch of tests for values that we're scraping:

class TestFilesizeConversions(TestCase):

def test_filesize_conversions(self):
"""Can we convert human filesizes to bytes?"""
qa_pairs = [
('58 kb', 59392),
('117 kb', 119808),
('117kb', 119808),
('1 byte', 1),
('117 bytes', 117),
('117 bytes', 117),
(' 117 bytes ', 117),
('117b', 117),
('117bytes', 117),
('1 kilobyte', 1024),
('117 kilobytes', 119808),
('0.7 mb', 734003),
('1mb', 1048576),
('5.2 mb', 5452595),
]
for qa in qa_pairs:
print("Converting '%s' to bytes..." % qa[0], end='')
self.assertEqual(convert_size_to_bytes(qa[0]), qa[1])
print('✓')


Related Topics



Leave a reply



Submit