Skip to main content

js_compile/
number.rs

1//! `Number::toString`, the one spelling of a number that both halves of the engine need.
2//!
3//! It lives here rather than in `quickjs-pure` because the **compiler** needs it too: a
4//! numeric property key is turned into an atom at compile time (`get 0.0000001() {}` binds
5//! the key `"1e-7"`), and that has to be the same string the runtime would produce. Two
6//! copies of the spec's algorithm would be two things to keep in step, and the exponent
7//! thresholds are exactly the part that is easy to get subtly wrong.
8//!
9//! `quickjs-pure` depends on this crate, so it re-exports [`number_to_string`] from here
10//! instead of owning it — see `quickjs_pure::value`.
11
12/// `ToString` applied to a number.
13///
14/// The thresholds are the ones the spec's `Number::toString` uses: exponential form below
15/// `1e-6` and from `1e21` up, decimal form in between. Within the decimal range Rust's
16/// shortest-round-trip formatter already agrees with JavaScript digit for digit — including
17/// the notorious `0.30000000000000004` — so only the exponent spelling has to be
18/// normalised.
19pub fn number_to_string(value: f64) -> String {
20    if value.is_nan() {
21        return "NaN".to_string();
22    }
23    if value.is_infinite() {
24        return if value > 0.0 {
25            "Infinity".to_string()
26        } else {
27            "-Infinity".to_string()
28        };
29    }
30    if value == 0.0 {
31        // `ToString(-0)` is `"0"`; `print(-0)` is a different question, which is why
32        // `quickjs-pure` keeps its own `number_to_string_for_print`.
33        return "0".to_string();
34    }
35    let magnitude = value.abs();
36    if magnitude >= 1e21 || magnitude < 1e-6 {
37        return normalise_exponent(format!("{value:e}"));
38    }
39    format!("{value}")
40}
41
42/// Turn Rust's `1e-7` / `1e21` into JavaScript's `1e-7` / `1e+21`.
43///
44/// A negative exponent already has its sign; a positive one needs the `+` the spec
45/// requires, and Rust leaves it out.
46fn normalise_exponent(text: String) -> String {
47    let Some((mantissa, exponent)) = text.split_once('e') else {
48        return text;
49    };
50    if exponent.starts_with('-') {
51        text
52    } else {
53        let digits = exponent.strip_prefix('+').unwrap_or(exponent);
54        format!("{mantissa}e+{digits}")
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::number_to_string;
61
62    /// The thresholds themselves, and one value either side of each. These are the cases a
63    /// hand-written formatter gets wrong, so they are the ones pinned down.
64    #[test]
65    fn the_exponent_thresholds_match_the_spec() {
66        assert_eq!(number_to_string(0.000001), "0.000001");
67        assert_eq!(number_to_string(0.0000001), "1e-7");
68        assert_eq!(number_to_string(1e21), "1e+21");
69        assert_eq!(number_to_string(1e20), "100000000000000000000");
70    }
71
72    #[test]
73    fn negative_zero_stringifies_to_plain_zero() {
74        assert_eq!(number_to_string(-0.0), "0");
75        assert_eq!(number_to_string(0.0), "0");
76    }
77
78    #[test]
79    fn the_awkward_decimal_keeps_every_digit() {
80        assert_eq!(number_to_string(0.1 + 0.2), "0.30000000000000004");
81    }
82
83    #[test]
84    fn the_non_finite_three_are_spelled_out() {
85        assert_eq!(number_to_string(f64::NAN), "NaN");
86        assert_eq!(number_to_string(f64::INFINITY), "Infinity");
87        assert_eq!(number_to_string(f64::NEG_INFINITY), "-Infinity");
88    }
89}