File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 :
16- raise ValueError ("whole cannot be zero." )
17- value = (part / whole ) * 100
18- return round (value , decimals ) if decimals is not None else value
18+ return 0.0
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 )
You can’t perform that action at this time.
0 commit comments