From 046a2175ab62935aad6fe97d969aeaba52ba6398 Mon Sep 17 00:00:00 2001 From: Mark Thom Date: Sun, 27 Mar 2022 11:28:10 -0600 Subject: [PATCH] use ryu to print floats with a modification for compatible syntax (#1368, #1372) --- Cargo.lock | 1 + Cargo.toml | 1 + src/heap_print.rs | 23 ++++++++++++++--------- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f6a5430f..ac766ca5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1532,6 +1532,7 @@ dependencies = [ "roxmltree", "rug", "rustyline", + "ryu", "select", "serial_test", "sha3", diff --git a/Cargo.toml b/Cargo.toml index e74616d7..62ef48f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -64,6 +64,7 @@ smallvec = "1.8.0" sodiumoxide = "0.2.6" static_assertions = "1.1.0" slice-deque = "0.3.0" +ryu = "1.0.9" [dev-dependencies] assert_cmd = "1.0.3" diff --git a/src/heap_print.rs b/src/heap_print.rs index 030e7c73..8fc2bbe2 100644 --- a/src/heap_print.rs +++ b/src/heap_print.rs @@ -484,17 +484,22 @@ pub fn fmt_float(mut fl: f64) -> String { fl = 0f64; } - if fl.fract() == 0f64 { - if fl.abs() >= 1.0e16 { - format!("{:.1e}", fl.trunc()) - } else { - format!("{:.1}", fl.trunc()) + let mut buffer = ryu::Buffer::new(); + let fl_str = buffer.format(fl); + + /* When printing floats with zero fractional parts in scientific notation, ryu + * prints "{integer part}e{exponent}" without a ".0" preceding "e", + * which is not valid ISO Prolog syntax. Add ".0" manually in this + * case. + */ + + if let Some(e_index) = fl_str.find('e') { + if !fl_str[0 .. e_index].contains('.') { + return fl_str[0 .. e_index].to_string() + ".0" + &fl_str[e_index ..]; } - } else if 0f64 < fl.fract().abs() && fl.fract().abs() <= 1.0e-16 { - format!("{0:.15e}", fl) - } else { - format!("{}", fl) } + + fl_str.to_string() } #[derive(Debug)] -- 2.54.0