from decimal import Decimal
templates = (
'format({v}, ".{p}E")',
# 'f"{{{v}:.{p}E}}"',
# '"{{:.{p}E}}".format({v})',
# '"%.{p}E" % ({v},)',
# 'format({v}, ".{p}e")'
# 'f"{{{v}:.{p}e}}"',
# '"{{:.{p}e}}".format({v})',
# '"%.{p}e" % ({v},)',
)
values = (
# 0,
# 0.0,
# -0.0,
# complex(0),
Decimal('0'),
Decimal('-0.0'),
# 0.001,
# Decimal('0.001'),
# 1,
# 1.0,
# Decimal('1'),
# 10,
# 10.0,
# Decimal('10'),
# 100,
# 100.0,
# Decimal('100'),
# 1234512345123451234512345,
# 1234512345123451234512345.0,
# Decimal('1234512345123451234512345'),
)
precision = (
0,
1,
2,
3,
# 4,
# 5,
# 6,
# 7,
# 8,
# 9,
# 10,
30,
# 100,
# 1000,
# 10000,
)
results = [
((expr := t.format(v=repr(v), p=p)), eval(expr))
for t in templates
for v in values
for p in precision
]
max_len_expr = max(len(expr) for expr, val in results)
for expr, val in results:
print(f"{expr}{' ' * ((max_len_expr)-len(expr))} {repr(val)}")
Test output
NOTE: The internal exponent of the Decimal, rather than its sign, is causing the difference.
It seams that precision will affect exponent.
In addition to the above behavior, the exponent is not padded to
two digits, which also makes it inconsistent with the built-in types.
Although the results are numerically correct, and the document
(https://docs.python.org/3/library/string.html#format-specification-mini-language)
does not limit the exponent when the coefficient is 0.
However, this can be confusing for users.
Maybe the document needs to add a description.
note, or change the result of Decimal typeto be consistent with built-in types.
Test script
Linked PRs