pythondecimalscientific-notation

How to prevent/suppress Decimal from using scientific notation?


In [1]: from decimal import Decimal

In [2]: Decimal('0.00000100') * Decimal('0.95')
Out[2]: Decimal('9.500E-7')

In [3]: Decimal('9.500E-7').quantize(Decimal('0.00000000'))
Out[3]: Decimal('9.5E-7')

How to suppress scientific notation, and get '0.00000095'?


Solution

  • You can format your output with the Format Specification Mini-Language

    from decimal import Decimal
    d = Decimal('9.5E-7')
    print(d)
    print(format(d, 'f'))
    print(f"{d:f}")
    

    Output:

    9.5E-7
    0.00000095
    0.00000095
    

    But if you're planing to override decimal.Decimal.__str__ or decimal.Decimal.__repr__ you'll have a hard time, because they are read-only.

    Edit 2025-01-07: added f-string example