Skip to content

Commit

Permalink
improve: preserve Decimal type when round-tripping (#66)
Browse files Browse the repository at this point in the history
* improve: preserve Decimal type when round-tripping

* Lower case e in decimal representation
  • Loading branch information
hukkin authored Jan 13, 2025
1 parent e11e00e commit 420897a
Show file tree
Hide file tree
Showing 2 changed files with 12 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).lower()
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
12 changes: 10 additions & 2 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,28 @@

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"),
"float-2E16": float("2E16"),
}
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
float-2E16 = 2e+16
"""
)

Expand Down

0 comments on commit 420897a

Please sign in to comment.