Difference between rounding using Decimal library and rounding using round() function in Python 3. I don't know whether to use the round() function or use the Decimal library to round numbers
Decimal
from decimal import*
getcontext().prec = 3
print(Decimal(10)/3)
3,33
round()
print(round(10/3,2))
3,33
I hope everyone can answer my questions
CodePudding user response:
They serve different purposes, you can use both. While you use the function round to perform an actual rounding action, as per the docs:
Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.
With decimal, you can get and set the context for which you want numerical variables to operate (and a lot more, but for the sake of your question, I will limit it to this)
from decimal import *
getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
InvalidOperation])
Thus allowing me to set it differently with:
getcontext().rounding = ROUND_UP
With the latter you are not rounding per se, but doing it as a consequence of the context you define.
The module design is centered around three concepts: the decimal number, the context for arithmetic, and signals.
The context for arithmetic is an environment specifying precision, rounding rules, limits on exponents, flags indicating the results of operations, and trap enablers which determine whether signals are treated as exceptions. Rounding options include ROUND_CEILING, ROUND_DOWN, ROUND_FLOOR, ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_UP, and ROUND_05UP.
CodePudding user response:
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()
always take argument as an integer, while you can pass string in Decimal()
You can pass Decimal
object in round function as well.
round()
documentation https://docs.python.org/3/library/functions.html#round
Decimal()
documentation https://docs.python.org/3/library/decimal.html#decimal-objects