decimal128 – Support for BSON Decimal128

    New in version 3.4.

    Note

    The Decimal128 BSON type requires MongoDB 3.4+.

    class bson.decimal128.Decimal128(value)

    BSON Decimal128 type:

    • Parameters

      • value: An instance of decimal.Decimal, string, or tuple of (high bits, low bits) from Binary Integer Decimal (BID) format.

    uses an instance of decimal.Context configured for IEEE-754 Decimal128 when validating parameters. Signals like , decimal.Inexact, and are trapped and raised as exceptions:

    1. >>> Decimal128(".13.1")
    2. Traceback (most recent call last):
    3. File "<stdin>", line 1, in <module>
    4. ...
    5. decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
    6. >>>
    7. >>> Decimal128("1E-6177")
    8. Traceback (most recent call last):
    9. decimal.Inexact: [<class 'decimal.Inexact'>]
    10. >>>
    11. >>> Decimal128("1E6145")
    12. Traceback (most recent call last):
    13. File "<stdin>", line 1, in <module>
    14. ...
    15. decimal.Overflow: [<class 'decimal.Overflow'>, <class 'decimal.Rounded'>]

    To ensure the result of a calculation can always be stored as BSON Decimal128 use the context returned by create_decimal128_context():

    To match the behavior of MongoDB’s Decimal128 implementation str(Decimal(value)) may not match str(Decimal128(value)) for NaN values:

    1. >>> Decimal128(Decimal('NaN'))
    2. >>> Decimal128(Decimal('-NaN'))
    3. Decimal128('NaN')
    4. Decimal128('NaN')
    5. >>> Decimal128(Decimal('-sNaN'))
    6. Decimal128('NaN')

    However, will return the exact value:

    Two instances of Decimal128 compare equal if their Binary Integer Decimal encodings are equal:

    1. >>> Decimal128('NaN') == Decimal128('NaN')
    2. True
    3. >>> Decimal128('NaN').bid == Decimal128('NaN').bid

    This differs from comparisons for NaN:

    • The Binary Integer Decimal (BID) encoding of this instance.

    • classmethod from_bid(value)

      Create an instance of Decimal128 from Binary Integer Decimal string.

      • Parameters

        • value: 16 byte string (128-bit IEEE 754-2008 decimal floating point in Binary Integer Decimal (BID) format).

    Returns an instance of appropriate for working with IEEE-754 128-bit decimal floating point values.