Python - 关于十进制算术的问题

oro*_*aki 2 python math decimal

我有三个与Python中的十进制算术有关的问题,其中所有三个都是最好的内联问题:

1)

>>> from decimal import getcontext, Decimal
>>> getcontext().prec = 6
>>> Decimal('50.567898491579878') * 1
Decimal('50.5679')
>>> # How is this a precision of 6? If the decimal counts whole numbers as
>>> # part of the precision, is that actually still precision?
>>> 
Run Code Online (Sandbox Code Playgroud)

2)

>>> from decimal import getcontext, Decimal
>>> getcontext().prec = 6
>>> Decimal('50.567898491579878')
Decimal('50.567898491579878')
>>> # Shouldn't that have been rounded to 6 digits on instantiation?
>>> Decimal('50.567898491579878') * 1
Decimal('50.5679')
>>> # Instead, it only follows my precision setting set when operated on.
>>> 
Run Code Online (Sandbox Code Playgroud)

3)

>>> # Now I want to save the value to my database as a "total" with 2 places.
>>> from decimal import Decimal
>>> # Is the following the correct way to get the value into 2 decimal places,
>>> # or is there a "better" way?
>>> x = Decimal('50.5679').quantize(Decimal('0.00'))
>>> x  # Just wanted to see what the value was
Decimal('50.57')
>>> foo_save_value_to_db(x)
>>> 
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 8

  1. 精度遵循sig figs,而不是小数位数.前者在科学应用中更有用.

  2. 原始数据永远不应该被破坏.相反,它在操作时会进行修剪.

  3. 这就是它的完成方式.