Python取整为两位数

时间:2017-06-23 11:02:35

标签: python python-2.7

以下是代码:

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

请帮助您了解如何获得我的预期结果

1 个答案:

答案 0 :(得分:0)

建议您查看快速打包,这样可以减少文件大小打印的内容。

 scala> val result = res11
 result: List[String] = List(id:1, count:23331, id:3, count:34123, id:4, count:4021)

 scala> result.map(elem => elem.split(":")(1))
 res12: List[String] = List(1, 23331, 3, 34123, 4, 4021)

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