Skip to content

Commit e24990e

Browse files
authored
Merge pull request #1 from spaceox1000/main
Update core.py
2 parents 6acadc7 + d5d71aa commit e24990e

1 file changed

Lines changed: 20 additions & 10 deletions

File tree

percentify/core.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,28 @@
1-
def percent(part: float, whole: float, decimals: int | None = 2) -> float:
1+
from typing import SupportsFloat
2+
3+
def percent(part: SupportsFloat, whole: SupportsFloat, decimals: int | None = 2) -> float:
24
"""
3-
Easily calculate what percentage `part` is of the `whole`.
5+
Calculate what percentage `part` is of the `whole`.
46
57
Args:
6-
part (float): The numerator.
7-
whole (float): The denominator.
8-
decimals (int | None): Number of decimal places to round.
9-
If None, no rounding is applied.
8+
part: The numerator.
9+
whole: The denominator.
10+
decimals: Number of decimal places to round to.
11+
If None, the raw percentage (unrounded float) is returned.
1012
1113
Returns:
12-
float: Percentage value.
13-
14+
float: Percentage value. If `whole` is 0, returns 0.0.
1415
"""
16+
whole = float(whole)
1517
if whole == 0:
1618
return 0.0
17-
value = (part / whole) * 100
18-
return round(value, decimals) if decimals is not None else value
19+
20+
value = float(part) / whole * 100.0
21+
22+
if decimals is None:
23+
return value
24+
25+
if decimals < 0:
26+
raise ValueError("`decimals` must be non-negative or None.")
27+
28+
return round(value, decimals)

0 commit comments

Comments
 (0)