Skip to content

Commit

Permalink
Use Decimal.quantize to specify precision
Browse files Browse the repository at this point in the history
rather than adding a precision property to FloatObject
  • Loading branch information
programmarchy committed Sep 5, 2022
1 parent 00f0ed7 commit 9766c75
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 31 deletions.
5 changes: 4 additions & 1 deletion PyPDF2/_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1921,8 +1921,11 @@ def _create_outline_item(
if color:
if isinstance(color, str):
color = hex_to_rgb(color)
prec = decimal.Decimal('1.00000')
outline_item.update(
{NameObject("/C"): ArrayObject([FloatObject(c, prec=5) for c in color])}
{NameObject("/C"): ArrayObject([
FloatObject(decimal.Decimal(c).quantize(prec)) for c in color
])}
)
if italic or bold:
format_flag = 0
Expand Down
12 changes: 1 addition & 11 deletions PyPDF2/generic/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,15 +227,8 @@ def readFromStream(


class FloatObject(decimal.Decimal, PdfObject):
def __init__(
self, value: Union[str, Any] = "0", context: Optional[Any] = None, prec: Optional[int] = None
) -> None:
self.value = value
self.context = context
self.prec = prec

def __new__(
cls, value: Union[str, Any] = "0", context: Optional[Any] = None, prec: Optional[int] = None
cls, value: Union[str, Any] = "0", context: Optional[Any] = None
) -> "FloatObject":
try:
return decimal.Decimal.__new__(cls, str_(value), context)
Expand All @@ -249,9 +242,6 @@ def __repr__(self) -> str:
if self == self.to_integral():
# If this is an integer, format it with no decimal place.
return str(self.quantize(decimal.Decimal(1)))
elif self.prec is not None:
# If a precision was specified, then use it.
return f"{self:.{self.prec}f}"
else:
# Otherwise, format it with a decimal place, taking care to
# remove any extraneous trailing zeros.
Expand Down
19 changes: 0 additions & 19 deletions tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -845,22 +845,3 @@ def test_create_string_object_force():
)
def test_float_object_decimal_to_string(value, expected):
assert repr(FloatObject(value)) == expected


@pytest.mark.parametrize(
("value", "prec", "expected"),
[
("0.12345", None, "0.12345"),
("0.12345", 3, "0.123"),
("123.12345", 3, "123.123"),
("1.01", None, "1.01"),
("1.010", 3, "1.010"),
("1.010", 2, "1.01"),
("1.010", 1, "1.0"),
("1.123", 5, "1.12300"),
("1", 1, "1"),
("1", 5, "1"),
]
)
def test_float_object_to_string_with_precision(value, prec, expected):
assert repr(FloatObject(value, prec=prec)) == expected

0 comments on commit 9766c75

Please sign in to comment.