class decimal.Decimal(value="0", context=None)
Construct a new Decimal
object based from value.
value can be an integer, string, tuple, float
, or another Decimal
object. If no value is given, returns Decimal('0')
. If value is a string, it should conform to the decimal numeric string syntax after leading and trailing whitespace characters are removed:
sign ::= '+' | '-' digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' indicator ::= 'e' | 'E' digits ::= digit [digit]... decimal-part ::= digits '.' [digits] | ['.'] digits exponent-part ::= indicator [sign] digits infinity ::= 'Infinity' | 'Inf' nan ::= 'NaN' [digits] | 'sNaN' [digits] numeric-value ::= decimal-part [exponent-part] | infinity numeric-string ::= [sign] numeric-value | [sign] nan
Other Unicode decimal digits are also permitted where digit
appears above. These include decimal digits from various other alphabets (for example, Arabic-Indic and Devanāgarī digits) along with the fullwidth digits '\uff10'
through '\uff19'
.
If value is a tuple
, it should have three components, a sign (0
for positive or 1
for negative), a tuple
of digits, and an integer exponent. For example, Decimal((0, (1, 4, 1, 4), -3))
returns Decimal('1.414')
.
If value is a float
, the binary floating point value is losslessly converted to its exact decimal equivalent. This conversion can often require 53 or more digits of precision. For example, Decimal(float('1.1'))
converts to Decimal('1.100000000000000088817841970012523233890533447265625')
.
The context precision does not affect how many digits are stored. That is determined exclusively by the number of digits in value. For example, Decimal('3.00000')
records all five zeros even if the context precision is only three.
The purpose of the context argument is determining what to do if value is a malformed string. If the context traps InvalidOperation
, an exception is raised; otherwise, the constructor returns a new Decimal with the value of NaN
.
Once constructed, Decimal
objects are immutable.
Changed in version 3.2: The argument to the constructor is now permitted to be a float
instance.
Changed in version 3.3: float
arguments raise an exception if the FloatOperation
trap is set. By default the trap is off.
Decimal floating point objects share many properties with the other built-in numeric types such as float
and int
. All of the usual math operations and special methods apply. Likewise, decimal objects can be copied, pickled, printed, used as dictionary keys, used as set elements, compared, sorted, and coerced to another type (such as float
or int
).
There are some small differences between arithmetic on Decimal objects and arithmetic on integers and floats. When the remainder operator %
is applied to Decimal objects, the sign of the result is the sign of the dividend rather than the sign of the divisor:
>>> (-7) % 4 1 >>> Decimal(-7) % Decimal(4) Decimal('-3')
The integer division operator //
behaves analogously, returning the integer part of the true quotient (truncating towards zero) rather than its floor, so as to preserve the usual identity x == (x // y) * y + x % y
:
>>> -7 // 4 -2 >>> Decimal(-7) // Decimal(4) Decimal('-1')
The %
and //
operators implement the remainder
and divide-integer
operations (respectively) as described in the specification.
Decimal objects cannot generally be combined with floats or instances of fractions.Fraction
in arithmetic operations: an attempt to add a Decimal
to a float
, for example, will raise a TypeError
. However, it is possible to use Python’s comparison operators to compare a Decimal
instance x
with another number y
. This avoids confusing results when doing equality comparisons between numbers of different types.
Changed in version 3.2: Mixed-type comparisons between Decimal
instances and other numeric types are now fully supported.
In addition to the standard numeric properties, decimal floating point objects also have a number of specialized methods:
-
adjusted()
-
Return the adjusted exponent after shifting out the coefficient’s rightmost digits until only the lead digit remains:
Decimal('321e+5').adjusted()
returns seven. Used for determining the position of the most significant digit with respect to the decimal point.
-
as_tuple()
-
Return a named tuple representation of the number:
DecimalTuple(sign, digits, exponent)
.
-
canonical()
-
Return the canonical encoding of the argument. Currently, the encoding of a
Decimal
instance is always canonical, so this operation returns its argument unchanged.
-
compare(other, context=None)
-
Compare the values of two Decimal instances.
compare()
returns a Decimal instance, and if either operand is a NaN then the result is a NaN:a or b is a NaN ==> Decimal('NaN') a < b ==> Decimal('-1') a == b ==> Decimal('0') a > b ==> Decimal('1')
-
compare_signal(other, context=None)
-
This operation is identical to the
compare()
method, except that all NaNs signal. That is, if neither operand is a signaling NaN then any quiet NaN operand is treated as though it were a signaling NaN.
-
compare_total(other, context=None)
-
Compare two operands using their abstract representation rather than their numerical value. Similar to the
compare()
method, but the result gives a total ordering onDecimal
instances. TwoDecimal
instances with the same numeric value but different representations compare unequal in this ordering:>>> Decimal('12.0').compare_total(Decimal('12')) Decimal('-1')
Quiet and signaling NaNs are also included in the total ordering. The result of this function is
Decimal('0')
if both operands have the same representation,Decimal('-1')
if the first operand is lower in the total order than the second, andDecimal('1')
if the first operand is higher in the total order than the second operand. See the specification for details of the total order.This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
-
compare_total_mag(other, context=None)
-
Compare two operands using their abstract representation rather than their value as in
compare_total()
, but ignoring the sign of each operand.x.compare_total_mag(y)
is equivalent tox.copy_abs().compare_total(y.copy_abs())
.This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
-
conjugate()
-
Just returns self, this method is only to comply with the Decimal Specification.
-
copy_abs()
-
Return the absolute value of the argument. This operation is unaffected by the context and is quiet: no flags are changed and no rounding is performed.
-
copy_negate()
-
Return the negation of the argument. This operation is unaffected by the context and is quiet: no flags are changed and no rounding is performed.
-
copy_sign(other, context=None)
-
Return a copy of the first operand with the sign set to be the same as the sign of the second operand. For example:
>>> Decimal('2.3').copy_sign(Decimal('-1.5')) Decimal('-2.3')
This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
-
exp(context=None)
-
Return the value of the (natural) exponential function
e**x
at the given number. The result is correctly rounded using theROUND_HALF_EVEN
rounding mode.>>> Decimal(1).exp() Decimal('2.718281828459045235360287471') >>> Decimal(321).exp() Decimal('2.561702493119680037517373933E+139')
-
from_float(f)
-
Classmethod that converts a float to a decimal number, exactly.
Note Decimal.from_float(0.1) is not the same as Decimal(‘0.1’). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. That equivalent value in decimal is 0.1000000000000000055511151231257827021181583404541015625.
Note
From Python 3.2 onwards, a
Decimal
instance can also be constructed directly from afloat
.>>> Decimal.from_float(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') >>> Decimal.from_float(float('nan')) Decimal('NaN') >>> Decimal.from_float(float('inf')) Decimal('Infinity') >>> Decimal.from_float(float('-inf')) Decimal('-Infinity')
New in version 3.1.
-
fma(other, third, context=None)
-
Fused multiply-add. Return self*other+third with no rounding of the intermediate product self*other.
>>> Decimal(2).fma(3, 5) Decimal('11')
-
is_canonical()
-
Return
True
if the argument is canonical andFalse
otherwise. Currently, aDecimal
instance is always canonical, so this operation always returnsTrue
.
-
is_finite()
-
Return
True
if the argument is a finite number, andFalse
if the argument is an infinity or a NaN.
-
is_infinite()
-
Return
True
if the argument is either positive or negative infinity andFalse
otherwise.
-
is_normal(context=None)
-
Return
True
if the argument is a normal finite number. ReturnFalse
if the argument is zero, subnormal, infinite or a NaN.
-
is_signed()
-
Return
True
if the argument has a negative sign andFalse
otherwise. Note that zeros and NaNs can both carry signs.
-
ln(context=None)
-
Return the natural (base e) logarithm of the operand. The result is correctly rounded using the
ROUND_HALF_EVEN
rounding mode.
-
log10(context=None)
-
Return the base ten logarithm of the operand. The result is correctly rounded using the
ROUND_HALF_EVEN
rounding mode.
-
logb(context=None)
-
For a nonzero number, return the adjusted exponent of its operand as a
Decimal
instance. If the operand is a zero thenDecimal('-Infinity')
is returned and theDivisionByZero
flag is raised. If the operand is an infinity thenDecimal('Infinity')
is returned.
-
logical_and(other, context=None)
-
logical_and()
is a logical operation which takes two logical operands (see Logical operands). The result is the digit-wiseand
of the two operands.
-
logical_invert(context=None)
-
logical_invert()
is a logical operation. The result is the digit-wise inversion of the operand.
-
logical_or(other, context=None)
-
logical_or()
is a logical operation which takes two logical operands (see Logical operands). The result is the digit-wiseor
of the two operands.
-
logical_xor(other, context=None)
-
logical_xor()
is a logical operation which takes two logical operands (see Logical operands). The result is the digit-wise exclusive or of the two operands.
-
max(other, context=None)
-
Like
max(self, other)
except that the context rounding rule is applied before returning and thatNaN
values are either signaled or ignored (depending on the context and whether they are signaling or quiet).
-
max_mag(other, context=None)
-
Similar to the
max()
method, but the comparison is done using the absolute values of the operands.
-
min(other, context=None)
-
Like
min(self, other)
except that the context rounding rule is applied before returning and thatNaN
values are either signaled or ignored (depending on the context and whether they are signaling or quiet).
-
min_mag(other, context=None)
-
Similar to the
min()
method, but the comparison is done using the absolute values of the operands.
-
next_minus(context=None)
-
Return the largest number representable in the given context (or in the current thread’s context if no context is given) that is smaller than the given operand.
-
next_plus(context=None)
-
Return the smallest number representable in the given context (or in the current thread’s context if no context is given) that is larger than the given operand.
-
next_toward(other, context=None)
-
If the two operands are unequal, return the number closest to the first operand in the direction of the second operand. If both operands are numerically equal, return a copy of the first operand with the sign set to be the same as the sign of the second operand.
-
normalize(context=None)
-
Normalize the number by stripping the rightmost trailing zeros and converting any result equal to
Decimal('0')
toDecimal('0e0')
. Used for producing canonical values for attributes of an equivalence class. For example,Decimal('32.100')
andDecimal('0.321000e+2')
both normalize to the equivalent valueDecimal('32.1')
.
-
number_class(context=None)
-
Return a string describing the class of the operand. The returned value is one of the following ten strings.
-
"-Infinity"
, indicating that the operand is negative infinity. -
"-Normal"
, indicating that the operand is a negative normal number. -
"-Subnormal"
, indicating that the operand is negative and subnormal. -
"-Zero"
, indicating that the operand is a negative zero. -
"+Zero"
, indicating that the operand is a positive zero. -
"+Subnormal"
, indicating that the operand is positive and subnormal. -
"+Normal"
, indicating that the operand is a positive normal number. -
"+Infinity"
, indicating that the operand is positive infinity. -
"NaN"
, indicating that the operand is a quiet NaN (Not a Number). -
"sNaN"
, indicating that the operand is a signaling NaN.
-
-
quantize(exp, rounding=None, context=None)
-
Return a value equal to the first operand after rounding and having the exponent of the second operand.
>>> Decimal('1.41421356').quantize(Decimal('1.000')) Decimal('1.414')
Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision, then an
InvalidOperation
is signaled. This guarantees that, unless there is an error condition, the quantized exponent is always equal to that of the right-hand operand.Also unlike other operations, quantize never signals Underflow, even if the result is subnormal and inexact.
If the exponent of the second operand is larger than that of the first then rounding may be necessary. In this case, the rounding mode is determined by the
rounding
argument if given, else by the givencontext
argument; if neither argument is given the rounding mode of the current thread’s context is used.An error is returned whenever the resulting exponent is greater than
Emax
or less thanEtiny
.
-
radix()
-
Return
Decimal(10)
, the radix (base) in which theDecimal
class does all its arithmetic. Included for compatibility with the specification.
-
remainder_near(other, context=None)
-
Return the remainder from dividing self by other. This differs from
self % other
in that the sign of the remainder is chosen so as to minimize its absolute value. More precisely, the return value isself - n * other
wheren
is the integer nearest to the exact value ofself / other
, and if two integers are equally near then the even one is chosen.If the result is zero then its sign will be the sign of self.
>>> Decimal(18).remainder_near(Decimal(10)) Decimal('-2') >>> Decimal(25).remainder_near(Decimal(10)) Decimal('5') >>> Decimal(35).remainder_near(Decimal(10)) Decimal('-5')
-
rotate(other, context=None)
-
Return the result of rotating the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to rotate. If the second operand is positive then rotation is to the left; otherwise rotation is to the right. The coefficient of the first operand is padded on the left with zeros to length precision if necessary. The sign and exponent of the first operand are unchanged.
-
same_quantum(other, context=None)
-
Test whether self and other have the same exponent or whether both are
NaN
.This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
-
scaleb(other, context=None)
-
Return the first operand with exponent adjusted by the second. Equivalently, return the first operand multiplied by
10**other
. The second operand must be an integer.
-
shift(other, context=None)
-
Return the result of shifting the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to shift. If the second operand is positive then the shift is to the left; otherwise the shift is to the right. Digits shifted into the coefficient are zeros. The sign and exponent of the first operand are unchanged.
-
sqrt(context=None)
-
Return the square root of the argument to full precision.
-
to_eng_string(context=None)
-
Convert to a string, using engineering notation if an exponent is needed.
Engineering notation has an exponent which is a multiple of 3. This can leave up to 3 digits to the left of the decimal place and may require the addition of either one or two trailing zeros.
For example, this converts
Decimal('123E+1')
toDecimal('1.23E+3')
.
-
to_integral(rounding=None, context=None)
-
Identical to the
to_integral_value()
method. Theto_integral
name has been kept for compatibility with older versions.
-
to_integral_exact(rounding=None, context=None)
-
Round to the nearest integer, signaling
Inexact
orRounded
as appropriate if rounding occurs. The rounding mode is determined by therounding
parameter if given, else by the givencontext
. If neither parameter is given then the rounding mode of the current context is used.
-
to_integral_value(rounding=None, context=None)
-
Round to the nearest integer without signaling
Inexact
orRounded
. If given, applies rounding; otherwise, uses the rounding method in either the supplied context or the current context.
Please login to continue.