Floating point class for decimal arithmetic.
| 521 | # numbers.py for more detail. |
| 522 | |
| 523 | class Decimal(object): |
| 524 | """Floating point class for decimal arithmetic.""" |
| 525 | |
| 526 | __slots__ = ('_exp','_int','_sign', '_is_special') |
| 527 | # Generally, the value of the Decimal instance is given by |
| 528 | # (-1)**_sign * _int * 10**_exp |
| 529 | # Special values are signified by _is_special == True |
| 530 | |
| 531 | # We're immutable, so use __new__ not __init__ |
| 532 | def __new__(cls, value="0", context=None): |
| 533 | """Create a decimal point instance. |
| 534 | |
| 535 | >>> Decimal('3.14') # string input |
| 536 | Decimal('3.14') |
| 537 | >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) |
| 538 | Decimal('3.14') |
| 539 | >>> Decimal(314) # int |
| 540 | Decimal('314') |
| 541 | >>> Decimal(Decimal(314)) # another decimal instance |
| 542 | Decimal('314') |
| 543 | >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay |
| 544 | Decimal('3.14') |
| 545 | """ |
| 546 | |
| 547 | # Note that the coefficient, self._int, is actually stored as |
| 548 | # a string rather than as a tuple of digits. This speeds up |
| 549 | # the "digits to integer" and "integer to digits" conversions |
| 550 | # that are used in almost every arithmetic operation on |
| 551 | # Decimals. This is an internal detail: the as_tuple function |
| 552 | # and the Decimal constructor still deal with tuples of |
| 553 | # digits. |
| 554 | |
| 555 | self = object.__new__(cls) |
| 556 | |
| 557 | # From a string |
| 558 | # REs insist on real strings, so we can too. |
| 559 | if isinstance(value, str): |
| 560 | m = _parser(value.strip().replace("_", "")) |
| 561 | if m is None: |
| 562 | if context is None: |
| 563 | context = getcontext() |
| 564 | return context._raise_error(ConversionSyntax, |
| 565 | "Invalid literal for Decimal: %r" % value) |
| 566 | |
| 567 | if m.group('sign') == "-": |
| 568 | self._sign = 1 |
| 569 | else: |
| 570 | self._sign = 0 |
| 571 | intpart = m.group('int') |
| 572 | if intpart is not None: |
| 573 | # finite number |
| 574 | fracpart = m.group('frac') or '' |
| 575 | exp = int(m.group('exp') or '0') |
| 576 | self._int = str(int(intpart+fracpart)) |
| 577 | self._exp = exp - len(fracpart) |
| 578 | self._is_special = False |
| 579 | else: |
| 580 | diag = m.group('diag') |
no outgoing calls
no test coverage detected