Skip to content
Merged
Show file tree
Hide file tree
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
6 changes: 4 additions & 2 deletions pyiceberg/expressions/literals.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,8 @@ def _(self, _: DoubleType) -> Literal[float]:
def _(self, type_var: DecimalType) -> Literal[Decimal]:
if not isfinite(self.value):
raise ValueError(f"Could not convert {self.value} into a {type_var}, value is not finite")
return DecimalLiteral(Decimal(self.value).quantize(Decimal((0, (1,), -type_var.scale)), rounding=ROUND_HALF_UP))
# Use the shortest repr of the float, like BigDecimal.valueOf in Java, so 2.675 rounds to 2.68
return DecimalLiteral(Decimal(str(self.value)).quantize(Decimal((0, (1,), -type_var.scale)), rounding=ROUND_HALF_UP))


class DoubleLiteral(Literal[float]):
Expand All @@ -443,7 +444,8 @@ def _(self, _: FloatType) -> Literal[float]:
def _(self, type_var: DecimalType) -> Literal[Decimal]:
if not isfinite(self.value):
raise ValueError(f"Could not convert {self.value} into a {type_var}, value is not finite")
return DecimalLiteral(Decimal(self.value).quantize(Decimal((0, (1,), -type_var.scale)), rounding=ROUND_HALF_UP))
# Use the shortest repr of the float, like BigDecimal.valueOf in Java, so 2.675 rounds to 2.68
return DecimalLiteral(Decimal(str(self.value)).quantize(Decimal((0, (1,), -type_var.scale)), rounding=ROUND_HALF_UP))


class DateLiteral(Literal[int]):
Expand Down
13 changes: 13 additions & 0 deletions tests/expressions/test_literals.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,19 @@ def test_double_to_decimal_conversion(decimal_type: DecimalType, decimal_value:
assert lit.to(decimal_type).value.as_tuple() == Decimal(decimal_value).as_tuple() # type: ignore


@pytest.mark.parametrize("literal_class", [FloatLiteral, DoubleLiteral])
@pytest.mark.parametrize(
"value, decimal_value",
[(2.675, "2.68"), (1.005, "1.01"), (-2.675, "-2.68"), (0.125, "0.13"), (2.674, "2.67")],
)
def test_float_and_double_to_decimal_round_half_up_on_shortest_repr(
literal_class: type[FloatLiteral] | type[DoubleLiteral], value: float, decimal_value: str
) -> None:
lit = literal_class(value)

assert lit.to(DecimalType(10, 2)).value.as_tuple() == Decimal(decimal_value).as_tuple()


def test_float_to_decimal_conversion_with_infinity() -> None:
lit = FloatLiteral(float("inf"))

Expand Down
Loading