ifc_lite_core/fmt_num.rs
1// SPDX-License-Identifier: MPL-2.0
2//! Canonical number-to-text for property values, the inverse of the float
3//! parsing core already owns.
4
5/// Format an f64 without noisy trailing zeros (`1.0` -> `1`, `1.50` -> `1.5`),
6/// and otherwise with the shortest digits that parse back to the same value
7/// (what JS `String(n)` shows for the same value in the ranges that matter).
8///
9/// The digits must round-trip: no fixed decimal count, so a small nonzero never
10/// reads as `0`. Integral values below 1e15 print as integers.
11pub fn fmt_num(v: f64) -> String {
12 if v.fract() == 0.0 && v.abs() < 1e15 {
13 format!("{}", v as i64)
14 } else {
15 format!("{v}")
16 }
17}
18
19#[cfg(test)]
20mod tests {
21 use super::fmt_num;
22
23 #[test]
24 fn integral_values_drop_the_fraction_and_others_round_trip() {
25 assert_eq!(fmt_num(200.0), "200");
26 assert_eq!(fmt_num(-0.0), "0");
27 assert_eq!(fmt_num(1.5), "1.5");
28 for v in [2.5e-7, 1234.56789012, 1e15, 0.1 + 0.2] {
29 assert_eq!(fmt_num(v).parse::<f64>().unwrap(), v);
30 }
31 assert_eq!(fmt_num(1e15), "1000000000000000");
32 }
33}