From 1bbc23702b7c68d5d5c7a8aff0f590bb2788cc35 Mon Sep 17 00:00:00 2001 From: evan Adam Date: Fri, 13 Jun 2025 18:51:16 +0200 Subject: [PATCH] enh(output): use a helper for decimal arbitrary precision --- experimental/src/compute/ast.rs | 2 +- experimental/src/output/mod.rs | 38 +++++++++++++++++++++++++++++---- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/experimental/src/compute/ast.rs b/experimental/src/compute/ast.rs index de8bc8acb..be3c5f879 100644 --- a/experimental/src/compute/ast.rs +++ b/experimental/src/compute/ast.rs @@ -316,7 +316,7 @@ impl ExprResult { *s = format!("{}{}", s, ss); } ExprResult::Number(n) => { - *s = format!("{}{}", s, n); + *s = format!("{}{:.2}", s, crate::output::float_string(n)); } _ => panic!("Unable to join objects others than strings"), }, diff --git a/experimental/src/output/mod.rs b/experimental/src/output/mod.rs index e85cbdfed..9acb65dfd 100644 --- a/experimental/src/output/mod.rs +++ b/experimental/src/output/mod.rs @@ -101,17 +101,17 @@ impl<'a> OutputFormatter<'a> { format!( "{}={};{};{};{};{}", m.name, - m.value, + float_string(&m.value), m.warning.unwrap_or(""), m.critical.unwrap_or(""), match m.min { - Some(min) => min.to_string(), + Some(min) => float_string(&min), None => "".to_string(), }, match m.max { - Some(max) => max.to_string(), + Some(max) => float_string(&max), None => "".to_string(), - }, + } ) }) .collect::>() @@ -185,3 +185,33 @@ impl<'a> OutputFormatter<'a> { std::format!("{}{}", prefix, "blabla") } } +pub fn float_string(val: &f64) -> String { + let mut s = format!("{:.2}", val); + while s.ends_with('0') { + s.pop(); + } + if s.ends_with('.') { + s.pop(); + } + s +} + +mod test { + + #[test] + fn test_float_string() { + use super::float_string; + + let f = f64::default(); + assert_eq!(float_string(&40.0), "40"); + assert_eq!(float_string(&40.00), "40"); + assert_eq!(float_string(&40.001), "40"); + assert_eq!(float_string(&40.009), "40.01"); + + assert_eq!(float_string(&40.01), "40.01"); + assert_eq!(float_string(&40.104), "40.1"); + + assert_eq!(float_string(&f), "0"); + assert_eq!(float_string(&9999999.999), "10000000"); + } +}