Python - вопрос о десятичной арифметике - PullRequest
2 голосов
/ 07 октября 2010

У меня есть 3 вопроса, относящихся к десятичной арифметике в Python, все 3 из которых лучше всего задать inline:

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

и

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

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

1 Ответ

8 голосов
/ 07 октября 2010
  1. Точность следует sig figs , а не дробные цифры.Первый более полезен в научных приложениях.

  2. Необработанные данные никогда не следует искажать.Вместо этого он выполняет калечащие операции при операции.

  3. Вот как это делается.

...