pub fn fmt_num(v: f64) -> String {
if !v.is_finite() {
return "0".to_string();
}
let rounded = if v.abs() <= f64::MAX / 100.0 {
(v * 100.0).round() / 100.0
} else {
v
};
let rounded = if rounded == 0.0 { 0.0 } else { rounded }; let mut s = format!("{rounded:.2}");
if s.contains('.') {
while s.ends_with('0') {
s.pop();
}
if s.ends_with('.') {
s.pop();
}
}
s
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_with_two_decimals() {
assert_eq!(fmt_num(1.0), "1");
assert_eq!(fmt_num(1.005), "1"); assert_eq!(fmt_num(1.5), "1.5");
assert_eq!(fmt_num(1.25), "1.25");
assert_eq!(fmt_num(1.234), "1.23");
assert_eq!(fmt_num(-0.0), "0"); assert_eq!(fmt_num(100.0), "100");
}
#[test]
fn non_finite_falls_back_to_zero() {
assert_eq!(fmt_num(f64::NAN), "0");
assert_eq!(fmt_num(f64::INFINITY), "0");
assert_eq!(fmt_num(f64::NEG_INFINITY), "0");
}
#[test]
fn fmt_num_huge_finite_does_not_emit_inf() {
let s = fmt_num(1e308);
assert!(!s.contains("inf") && !s.contains("NaN"), "got {s}");
assert_ne!(s, "0", "huge finite must not collapse to 0: {s}");
assert!(s.starts_with('1') && s.len() > 100, "got {s}");
}
}