Skip to content
Merged
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
30 changes: 20 additions & 10 deletions percentify/core.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
def percent(part: float, whole: float, decimals: int | None = 2) -> float:
from typing import SupportsFloat

def percent(part: SupportsFloat, whole: SupportsFloat, decimals: int | None = 2) -> float:
"""
Easily calculate what percentage `part` is of the `whole`.
Calculate what percentage `part` is of the `whole`.

Args:
part (float): The numerator.
whole (float): The denominator.
decimals (int | None): Number of decimal places to round.
If None, no rounding is applied.
part: The numerator.
whole: The denominator.
decimals: Number of decimal places to round to.
If None, the raw percentage (unrounded float) is returned.

Returns:
float: Percentage value.

float: Percentage value. If `whole` is 0, returns 0.0.
"""
whole = float(whole)
if whole == 0:
return 0.0
value = (part / whole) * 100
return round(value, decimals) if decimals is not None else value

value = float(part) / whole * 100.0

if decimals is None:
return value

if decimals < 0:
raise ValueError("`decimals` must be non-negative or None.")

return round(value, decimals)