diff --git a/crates/formula/src/printer.rs b/crates/formula/src/printer.rs index e69351168..62d59bff3 100644 --- a/crates/formula/src/printer.rs +++ b/crates/formula/src/printer.rs @@ -154,7 +154,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), + } + } +}