【问题标题】:How to round number in Python (many digits after comma)如何在 Python 中舍入数字(逗号后有多个数字)
【发布时间】:2020-12-07 14:32:22
【问题描述】:

如何打印具有 2.6000000000000001 的 2.7。 (或任何其他类似的数字)。

import math

print(math.ceil(2.6000000000000001))  // 3
print(round(2.6000000000000001, 2))  // 2.6

???

【问题讨论】:

  • ceil(x * 10) / 10 或。确保在逗号后只打印一个位置f"{ceil(x * 10) / 10:.1f}"

标签: python-3.x math rounding


【解决方案1】:

如果您想以通用方式执行此操作并使用不同的位数,here 是一个示例,说明如何为自己定义相应的函数:

import math

def round_decimals_up(number:float, decimals:int=1):
    if not isinstance(decimals, int):
        raise TypeError("decimal places must be an integer")
    elif decimals < 0:
        raise ValueError("decimal places needs to be 0 or more")
    elif decimals == 0:
        return math.ceil(number)

    factor = 10 ** decimals
    return math.ceil(number * factor) / factor

我将其调整为默认为一位十进制数字,但它也允许您指定位数:

x = 2.6
y = 2.60000000001

print(round_decimals_up(x))
print(round_decimals_up(y))
print(round_decimals_up(x,2))
print(round_decimals_up(y,2))

产量

2.6
2.7
2.6
2.61

【讨论】:

    【解决方案2】:
    import math
    
    num=2.6000000000000001
    digits=1
    
    t1=10**digits
    math.ceil(num*t1)/t1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-14
      • 2022-09-28
      • 2017-04-13
      • 2023-03-11
      • 2020-11-18
      • 2022-01-17
      • 2022-01-03
      • 1970-01-01
      相关资源
      最近更新 更多