两个数字的Python四舍五入

2024-06-08 02:03:33 发布

您现在位置:Python中文网/ 问答频道 /正文

代码如下:

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

以下是示例输出:

 1.125TB


 1.406TB

预期产量:

 1.12TB


 1.41TB

当我的精度值为2时,我得到的是1.13TB,但我需要四舍五入到1.12TB。你知道吗

基本上是1.125TB,我需要两个小数点。1.125四舍五入为1.13,但应四舍五入为1.12,1.406TB应四舍五入为1.41TB

你能帮我怎样得到我期望的结果吗


Tags: ofto代码numberifbytesstepunit
1条回答
网友
1楼 · 发布于 2024-06-08 02:03:33

我建议你去看看匆忙的软件包,当涉及到文件大小的打印时,它会使事情变得简单一些。你知道吗

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

相关问题 更多 >

    热门问题