When stored in a database, the use of Bytes is more accurate, scalable, and highly flexible.
When you output, you need to do some matching.
1. Precautions and Test code
- You need to consider the scenario where sizeInBytes is None.
- Divide by 1024.0 rather than 1024 to avoid loss of precision.
The implemented function is GETSIZEINMB (sizeinbytes), and the generic test code is
def GETSIZEINMB (sizeinbytes): return 0def Test (sizeinbytes): print '%s,%s '% (sizeInBytes, GETSIZEINMB ( sizeinbytes)) test (None) test (0) test (10240000) test (1024*1024*10)
2. Output in MB--return float
In general, the size of the ebook between 1-50MB, the output of a unified conversion to MB is a good choice.
Disadvantages:
- Output accuracy is too high, such as 10240000 Bytes calculation results of 10240000-9.765625
- File size is limited, less than 1 MB or G-level data is not suitable for this presentation
Advantage:
- Suitable for participating in calculations with return values
def GETSIZEINMB (sizeinbytes): return (sizeinbytes or 0)/(1024.0*1024.0)
3. Keep 1 decimal places in megabytes--return str
With precision in mind, you can choose to retain 1 decimal places.
def GETSIZEINMB (sizeinbytes): return '%.1f '% ((sizeinbytes or 0)/(1024.0*1024.0),) # use 1-dimension tuple is Suggested
The return value is suggested as '%.1f '% (number,) rather than '%.1f '%
Both can be executed correctly, but the latter is easily misjudged as a function that executes only one parameter number, leading to difficult-to-judge errors.
3. Keep up to 1 decimal places in megabytes--return str
Most operating systems typically display up to 1 decimal places
def GETSIZEINMB (sizeinbytes): sizeinmb = '%.1f '% ((sizeinbytes or 0)/(1024.0*1024.0),) # use 1-dimension tuple is suggested return sizeinmb[:-2] if Sizeinmb.endswith ('. 0 ') Else SIZEINMB # python2.5+ Required
4. Automatically select the best unit
def getsizeinnicestring (sizeinbytes): "" " Convert the given byteCount into a string LIKE:9.9BYTES/KB/MB/GB "" For (cutoff, label) in [(1024*1024*1024, "GB"), ( 1024*1024, "MB"), (1024x768, "KB"), ]: if sizeInBytes >= cutoff: return "%.1f%s"% (sizeInBytes * 1.0/cutoff, label) if sizeinbytes = = 1: return "1 byte" else: bytes = "%.1f"% (sizeinbytes or 0,) return (Bytes[:-2] if Bytes.endswith ('. 0 ') Else bytes) + ' bytes '
Algorithm Description:
1. From the English grammar point of view, only 1 uses the singular form. The other 0/decimals are in plural form. Bytes level involved
2. In terms of accuracy, KB and above, retain 1 decimal places. Bytes Reserves up to 1 decimal places.
This processing rule is not suitable for cases where decimals are very bit 0, such as 10.0 bytes,10.01 bytes. The input results are all bytes.
In other cases, there is no problem with precision.
Test data and results such as
Friendly output of file size and its Python implementation