Functional Weave
Code in Python

charts.format@1.0.0

impl/rust/format_percent.rs

748 bytes · the Rust 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.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::math_round_float::round_float;  ← from math.round-float ^1.0.0 · built alongside by fune
use super::text_format_decimal::format_decimal;  ← from text.format-decimal ^1.0.0 · built alongside by fune

/// 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%".
///
/// # Panics
/// Panics if the value is not finite or `decimals` is outside 0..=12.
pub fn format_percent(value: f64, decimals: i64) -> String {
    if !value.is_finite() {
        panic!("value must be a finite number, received {}", value);
    }
    let percent = round_float(value * 100.0, 12);
    format!("{}%", format_decimal(percent, decimals, false, ""))
}

pub fn fune_vector(args: &[Value]) -> Value {
    Value::str(&format_percent(args[0].as_f64(), args[1].as_i64()))
}