Skip to content

Commit

Permalink
improve: preserve Decimal type when round-tripping
Browse files Browse the repository at this point in the history
  • Loading branch information
hukkin committed Jan 9, 2025
1 parent e11e00e commit 9c77cbb
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
3 changes: 2 additions & 1 deletion src/tomli_w/_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,8 @@ def format_decimal(obj: Decimal) -> str:
return "inf"
if obj == Decimal("-inf"):
return "-inf"
return str(obj)
dec_str = str(obj)
return dec_str if "." in dec_str or "E" in dec_str else dec_str + ".0"


def format_inline_table(obj: Mapping, ctx: Context) -> str:
Expand Down
10 changes: 8 additions & 2 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,26 @@

def test_decimal():
obj = {
"decimal-0": Decimal(0),
"decimal-0": Decimal("0"),
"decimal-4": Decimal("4"),
"decimal-pi": Decimal("3.14159"),
"decimal-inf": Decimal("inf"),
"decimal-minus-inf": Decimal("-inf"),
"decimal-nan": Decimal("nan"),
"decimal-2e3": Decimal("2e3"),
"decimal-2E3": Decimal("2E3"),
}
assert (
tomli_w.dumps(obj)
== """\
decimal-0 = 0
decimal-0 = 0.0
decimal-4 = 4.0
decimal-pi = 3.14159
decimal-inf = inf
decimal-minus-inf = -inf
decimal-nan = nan
decimal-2e3 = 2E+3
decimal-2E3 = 2E+3
"""
)

Expand Down

0 comments on commit 9c77cbb

Please sign in to comment.