P i
P i

Reputation: 30734

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'?

Upvotes: 2

Views: 819

Answers (1)

Mike Scotty
Mike Scotty

Reputation: 10782

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

Upvotes: 7

Related Questions