Functional Weave
Code in Python

charts.format@1.0.0

impl/python/format_tick.py

770 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 places_for(x: float) -> int:
    """The fewest decimal places (0 to 12) that write x exactly; 12 if none do."""
    a = abs(float(x))
    for d in range(12):
        if round_float(a, d) == a:
            return d
    return 12


def format_tick(value: float, step: float) -> str:
    """A tick label with as many decimal places as the step needs, comma-grouped."""
    if isinstance(step, bool) or not isinstance(step, (int, float)) or not math.isfinite(step):
        raise ValueError("step must be a finite number, received %r" % (step,))
    places = places_for(value) if step == 0 else places_for(step)
    return format_decimal(value, places, False, ",")