Skip to content

Commit

Permalink
Ensure failure when non int precision is given
Browse files Browse the repository at this point in the history
Weird results can occur if a not integer is given as a precision.
Raise an exception if a floating point value is given.
  • Loading branch information
facelessuser committed Sep 16, 2024
1 parent 186e407 commit 945cd46
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 0 deletions.
3 changes: 3 additions & 0 deletions coloraide/algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,9 @@ def order(x: float) -> int:
def round_half_up(n: float, scale: int = 0) -> float:
"""Round half up."""

if not isinstance(scale, int):
raise ValueError("'float' object cannot be interpreted as an integer")

mult = 10.0 ** scale
return math.floor(n * mult + 0.5) / mult

Expand Down
2 changes: 2 additions & 0 deletions tests/test_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -1113,6 +1113,8 @@ def test_round(self):
self.assertEqual(alg.round_half_up(3.5), 4)
self.assertEqual(alg.round_half_up(3.9), 4)
self.assertEqual(alg.round_half_up(4), 4)
with self.assertRaises(ValueError):
alg.round_half_up(3.56, 3.4)

def test_scale(self):
"""Test rounding."""
Expand Down

0 comments on commit 945cd46

Please sign in to comment.