From 9cbb674c550e1bdca3a2be9a008e8a455b00f3f8 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:34:06 +0200 Subject: [PATCH] Print numbers near f64::MAX in a form that parses back Found while testing crates/formula/src/printer.rs:134 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/formula/src/printer.rs | 11 ++++++++++- crates/formula/tests/printer_roundtrip.rs | 15 +++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 crates/formula/tests/printer_roundtrip.rs diff --git a/crates/formula/src/printer.rs b/crates/formula/src/printer.rs index 055b0f145..ba659c188 100644 --- a/crates/formula/src/printer.rs +++ b/crates/formula/src/printer.rs @@ -132,7 +132,16 @@ fn write_struct_ref(s: &StructRef, at_shorthand: bool) -> String { } fn number(n: f64) -> String { - number_to_text(n) + let text = number_to_text(n); + // 15 significant digits can round past f64::MAX, which no longer parses. + if text.parse::().is_ok_and(f64::is_finite) { + return text; + } + let exact = format!("{:E}", n); + match exact.split_once('E') { + Some((m, e)) if !e.starts_with('-') => format!("{m}E+{e}"), + _ => exact, + } } /// Prints an expression in A1 notation. diff --git a/crates/formula/tests/printer_roundtrip.rs b/crates/formula/tests/printer_roundtrip.rs new file mode 100644 index 000000000..206e5efff --- /dev/null +++ b/crates/formula/tests/printer_roundtrip.rs @@ -0,0 +1,15 @@ +use gridcraft_formula::{Expr, parse, print}; + +#[test] +fn number_near_f64_max_round_trips() { + for src in ["=1.7976931348623157E308", "=-1.7976931348623157E308"] { + let e = parse(src).unwrap(); + let printed = print(&e); + let back = parse(&printed).unwrap_or_else(|err| panic!("{printed}: {err:?}")); + assert_eq!(print(&back), printed); + match (&e, &back) { + (Expr::Number(a), Expr::Number(b)) => assert_eq!(a, b), + _ => assert_eq!(e, back), + } + } +}