Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions fhir_core/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,10 +419,22 @@ def __get_pydantic_core_schema__(
"""

def _serialize(
value: typing.Union[str],
value: typing.Any,
info: core_schema.SerializationInfo,
) -> typing.Union[float]:
"""Encodes a Decimal as float."""
) -> typing.Union[int, float]:
"""Encodes a Decimal preserving precision.

Per the FHIR spec, decimal precision is significant:
Decimal('19') and Decimal('19.0') are clinically distinct values.
Whole-number Decimals (exponent >= 0) are serialized as int
to avoid a trailing .0 in JSON output.
"""
if isinstance(value, str):
value = decimal.Decimal(value)
if isinstance(value, decimal.Decimal):
exp = value.as_tuple().exponent
if isinstance(exp, int) and exp >= 0:
return int(value)
return float(value)

def _validate(
Expand Down Expand Up @@ -456,7 +468,6 @@ def _validate(
_serialize,
info_arg=True,
when_used="always",
return_schema=core_schema.decimal_schema(),
),
)

Expand Down