import math from .math_round_float import round_float from .text_format_decimal import format_decimal 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, ",")