【问题标题】:Decimal library and round() function十进制库和 round() 函数
【发布时间】:2022-11-13 23:57:48
【问题描述】:

Python 3 中使用 Decimal 库进行舍入和使用 round() 函数进行舍入的区别。 我不知道是使用 round() 函数还是使用 Decimal 库对数字进行四舍五入

十进制

from decimal import*
getcontext().prec = 3
print(Decimal(10)/3)

3,33

圆形的()

print(round(10/3,2))

3,33

希望大家能回答我的问题

【问题讨论】:

  • 答案是一样的。你的问题到底是什么?

标签: python python-3.x python-decimal


【解决方案1】:

它们有不同的用途,您可以同时使用。根据文档,当您使用函数 round 执行实际舍入操作时:

返回小数点后四舍五入到 ndigits 精度的数字。如果 ndigits 被省略或为 None,则返回最接近其输入的整数。

使用decimal,您可以获取并设置您希望数值变量运行的上下文(以及更多,但为了您的问题,我将其限制为此)

from decimal import *
getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
        InvalidOperation])

因此,我可以通过以下方式对其进行不同的设置:

getcontext().rounding = ROUND_UP

对于后者,您本身并不是四舍五入,而是根据您定义的上下文进行舍入。

模块设计围绕三个概念:十进制数、算术上下文和信号。

算术的上下文是指定精度、舍入规则、指数限制、指示操作结果的标志以及确定信号是否被视为异常的陷阱启用程序的环境。舍入选项包括 ROUND_CEILING、ROUND_DOWN、ROUND_FLOOR、ROUND_HALF_DOWN、ROUND_HALF_EVEN、ROUND_HALF_UP、ROUND_UP 和 ROUND_05UP。

【讨论】:

    【解决方案2】:
    from decimal import *
    print(Decimal("3.33"))
    #output
    Decimal('3.33')
    # These Decimal objects can be converted to float(), int(), etc. and can be fed to round functions as well.
    
    print(round(Decimal("3.33")))
    #ouput
    3
    
    print(round('3.33'))
    #output
    TypeError: type str doesn't define __round__ method
    

    round() 始终将参数作为整数,而您可以在 Decimal() 中传递字符串

    您也可以在圆形函数中传递Decimal 对象。

    round() 文档 https://docs.python.org/3/library/functions.html#round

    Decimal()文档https://docs.python.org/3/library/decimal.html#decimal-objects

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      相关资源
      最近更新 更多