简体   繁体   English

Python四舍五入为两位数

[英]Python round off for two digit

Below is the code: 下面是代码:

if number_of_bytes < 0:
    raise ValueError("!!! numberOfBytes can't be smaller than 0 !!!")
step_to_greater_unit = 1024.
number_of_bytes = float(number_of_bytes)
unit = 'bytes'
if (number_of_bytes / step_to_greater_unit) >= 1:
    number_of_bytes /= step_to_greater_unit
    unit = 'KB'
if (number_of_bytes / step_to_greater_unit) >= 1:
    number_of_bytes /= step_to_greater_unit
    unit = 'MB'
if (number_of_bytes / step_to_greater_unit) >= 1:
    number_of_bytes /= step_to_greater_unit
    unit = 'GB'
if (number_of_bytes / step_to_greater_unit) >= 1:
    number_of_bytes /= step_to_greater_unit
    unit = 'TB'
precision = 3
number_of_bytes = round(number_of_bytes, precision)
print number_of_bytes
size = str(number_of_bytes) + '' + unit

Below is the sample output: 下面是示例输出:

 1.125TB


 1.406TB

Expected output: 预期产量:

 1.12TB


 1.41TB

when my precision value is 2 I am getting 1.13TB but I need to round off to 1.12TB . 当我的精度值为2时,我将获得1.13TB,但我需要四舍五入为1.12TB。

Basically 1.125TB I need two decimal points. 基本上1.125TB,我需要两个小数点。 1.125 is rounding off to 1.13 but it should round of to 1.12 and 1.406TB should round off to 1.41TB 1.125四舍五入为1.13,但应四舍五入为1.12,1.406TB应四舍五入为1.41TB

Could you please help how to get my expected result 你能帮我得到我预期的结果吗

Would suggest you to look into the hurry package, which eases things a bit when it comes to file size prints. 建议您研究一下hurry软件包,这在文件大小打印方面会有所缓解。

>>> from hurry.filesize import alternative
>>> size(1, system=alternative)
'1 byte'
>>> size(10, system=alternative)
'10 bytes'
>>> size(1024, system=alternative)
'1 KB'

https://pypi.python.org/pypi/hurry.filesize https://pypi.python.org/pypi/hurry.filesize

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM