Functional Weave
Code in Python

charts.format@1.0.0

impl/python/format_percent.py

603 bytes · the Python implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import math

from .math_round_float import round_float  ← from math.round-float ^1.0.0 · built alongside by fune
from .text_format_decimal import format_decimal  ← from text.format-decimal ^1.0.0 · built alongside by fune


def format_percent(value: float, decimals: int) -> str:
    """A fraction as a percentage with fixed places; the product is cleaned of
    binary noise at 12 places first, so 0.145 is "15%", not "14%"."""
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
        raise ValueError("value must be a finite number, received %r" % (value,))
    percent = round_float(float(value) * 100, 12)
    return format_decimal(percent, decimals, False, "") + "%"