f64 -> string: shortest round-trip digits, fixed for exponents in (-4, 16], else scientific with sign and ≥2 exp digits; always includes `.0` or exponent so floats never read as ints. */
(f: f64)
| 1 | /* f64 -> string: shortest round-trip digits, fixed for exponents in (-4, 16], else scientific with sign and ≥2 exp digits; always includes `.0` or exponent so floats never read as ints. */ |
| 2 | pub fn format_f64(f: f64) -> alloc::string::String { |
| 3 | use alloc::string::String; |
| 4 | use core::fmt::Write; |
| 5 | if f.is_nan() { return String::from("nan"); } |
| 6 | if f == f64::INFINITY { return String::from("inf"); } |
| 7 | if f == f64::NEG_INFINITY { return String::from("-inf"); } |
| 8 | if f == 0.0 { |
| 9 | return if f.is_sign_negative() { String::from("-0.0") } else { String::from("0.0") }; |
| 10 | } |
| 11 | |
| 12 | // Rust's `{:e}` yields the same unique shortest mantissa dtoa does: "d[.ddd]eN". |
| 13 | let neg = f < 0.0; |
| 14 | let mut sci = String::with_capacity(32); |
| 15 | let _ = write!(&mut sci, "{:e}", f.abs()); |
| 16 | let (mant, exp_str) = sci.split_once('e').unwrap_or((sci.as_str(), "0")); |
| 17 | let exp: i32 = exp_str.parse().unwrap_or(0); |
| 18 | // Significant digits with the point removed; `decpt` = count of digits left of the point. |
| 19 | let mut digits = String::with_capacity(mant.len()); |
| 20 | for c in mant.chars() { if c != '.' { digits.push(c); } } |
| 21 | let decpt = exp + 1; |
| 22 | let ndig = digits.len() as i32; |
| 23 | |
| 24 | let mut out = String::with_capacity(digits.len() + 8); |
| 25 | if neg { out.push('-'); } |
| 26 | if decpt > -4 && decpt <= 16 { |
| 27 | if decpt <= 0 { |
| 28 | out.push_str("0."); |
| 29 | for _ in 0..(-decpt) { out.push('0'); } |
| 30 | out.push_str(&digits); |
| 31 | } else if decpt >= ndig { |
| 32 | out.push_str(&digits); |
| 33 | for _ in 0..(decpt - ndig) { out.push('0'); } |
| 34 | out.push_str(".0"); |
| 35 | } else { |
| 36 | let (l, r) = digits.split_at(decpt as usize); |
| 37 | out.push_str(l); |
| 38 | out.push('.'); |
| 39 | out.push_str(r); |
| 40 | } |
| 41 | } else { |
| 42 | let mut chars = digits.chars(); |
| 43 | out.push(chars.next().unwrap_or('0')); |
| 44 | let rest: String = chars.collect(); |
| 45 | if !rest.is_empty() { out.push('.'); out.push_str(&rest); } |
| 46 | out.push('e'); |
| 47 | let e = decpt - 1; |
| 48 | out.push(if e < 0 { '-' } else { '+' }); |
| 49 | let ea = e.unsigned_abs(); |
| 50 | if ea < 10 { out.push('0'); } |
| 51 | let mut nb = itoa::Buffer::new(); |
| 52 | out.push_str(nb.format(ea)); |
| 53 | } |
| 54 | out |
| 55 | } |
| 56 | |
| 57 | #[macro_export] |
| 58 | macro_rules! s { |