Skip to content

Commit 63f1c9b

Browse files
normalized scientific e, E format to match C++ conventions
1 parent d5d70c4 commit 63f1c9b

File tree

2 files changed

+26
-17
lines changed

2 files changed

+26
-17
lines changed

src/pyprintf/core.py

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -535,30 +535,39 @@ def sprintf_format(
535535

536536
elif placeholder.type in ("e", "E"):
537537
try:
538-
if placeholder.precision:
538+
# Get precision (default to 6 if not specified)
539+
if placeholder.precision is not None:
539540
try:
540-
precision = (
541-
int(placeholder.precision) if placeholder.precision else 6
542-
)
541+
precision = int(placeholder.precision) if placeholder.precision else 6
543542
except ValueError:
544543
precision = 6
545544
else:
546545
precision = 6
547-
546+
548547
# Format with scientific notation
549548
float_val = float(arg)
550-
551-
# Special case for whole numbers - produce simpler output
552-
if float_val == int(float_val):
553-
arg = f"{int(float_val)}e+0"
549+
550+
# Always use full precision format (like C++)
551+
mantissa_format = f"{{:.{precision}f}}"
552+
mantissa = mantissa_format.format(float_val if abs(float_val) < 1 else float_val / (10 ** int(f"{float_val:e}".split('e')[1])))
553+
554+
# Get exponent
555+
if float_val == 0:
556+
exponent = "+00"
554557
else:
555-
# Regular scientific notation with precision
556-
arg = f"{float_val:.{precision}e}"
557-
558-
arg = arg.upper() if placeholder.type == "E" else arg
559-
558+
exponent_val = int(f"{float_val:e}".split('e')[1])
559+
exponent_sign = "+" if exponent_val >= 0 else "-"
560+
exponent = f"{exponent_sign}{abs(exponent_val):02d}"
561+
562+
# Combine to match C++ format (always showing all decimal places)
563+
arg = f"{mantissa}e{exponent}"
564+
565+
# Handle uppercase for E format
566+
if placeholder.type == "E":
567+
arg = arg.upper()
568+
560569
except (ValueError, TypeError):
561-
arg = "0.000000e+00"
570+
arg = "0.000000e+00" if placeholder.type == "e" else "0.000000E+00"
562571

563572
elif placeholder.type == "f":
564573
try:

tests/test_sprintf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,10 @@ def test_format_a_json_array(self):
4343
assert sprintf("%j", ["foo", "bar"]) == json.dumps(["foo", "bar"])
4444

4545
def test_format_a_number_in_scientific_notation_lowercase(self):
46-
assert sprintf("%e", 2) == "2e+0"
46+
assert sprintf("%e", 2) == "2.000000e+00"
4747

4848
def test_format_a_number_in_scientific_notation_uppercase(self):
49-
assert sprintf("%E", 2) == "2E+0"
49+
assert sprintf("%E", 2) == "2.000000E+00"
5050

5151
def test_format_an_unsigned_decimal_integer(self):
5252
assert sprintf("%u", 2) == "2"

0 commit comments

Comments
 (0)