//! The JavaScript number operations this crate's engines lean on, where Rust's //! own spelling of the same name means something else. //! //! `crate::js` holds the string-valued ones (`number_to_string` //! and friends); these are the arithmetic ones, and they live here because they //! are the ENGINES' need, not the store's. /// `Math.round` — a half rounds UP (toward +infinity), where Rust's /// `f64::round` rounds a half AWAY FROM ZERO. /// /// The two disagree at exactly `-0.5`, `-1.5`, … — `Math.round(-0.5)` is `-0` /// and `(-0.5f64).round()` is `-1`. Anywhere a half can be reached from real /// data, that is a component quantised one step off or an occurrence a day out. /// /// It is NOT simply `floor(x + 0.5)`, which is the identity the spec itself /// gives and then excepts: `0.49999999999999994 + 0.5` rounds UP to exactly /// `1.0` in binary floating point, so the shortcut answers 1 where JavaScript /// answers 0. The spec's rule is "the closest integral Number, ties to the /// larger", and the two carve-outs below are where that differs from the /// shortcut. pub fn math_round(value: f64) -> f64 { if !value.is_finite() { return value; } let floor = value.floor(); // `value - floor` is exact for everything with a fractional part, and 0 for // everything too large to have one — which is why the big integers come // back untouched instead of gaining an ulp. let rounded = if value - floor < 0.5 { floor } else { floor + 1.0 }; // `Math.round` answers `-0` for `-0`, `-0.5` and everything between; a // plain `0.0` here would be a different Number in JavaScript's own terms. if rounded == 0.0 && value.is_sign_negative() { -0.0 } else { rounded } } #[cfg(test)] mod tests { use super::*; /// The disagreement, spelled out — Node's own answers. #[test] fn rounds_a_half_up_the_way_javascript_does() { let vectors: &[(f64, f64)] = &[ (0.5, 1.0), (1.5, 2.0), (2.5, 3.0), (-0.5, 0.0), (-1.5, -1.0), (-2.5, -2.0), (0.49999999999999994, 0.0), (-0.49999999999999994, 0.0), (0.0, 0.0), (-0.0, 0.0), (127.4, 127.0), (-127.5, -127.0), ]; for (input, expected) in vectors { assert_eq!(math_round(*input), *expected, "for {input}"); } // Rust's own `round` differs on exactly the negative halves. assert_eq!((-1.5f64).round(), -2.0); assert_eq!(math_round(-1.5), -1.0); // And the sign of a zero is preserved, as `Math.round` preserves it. assert!(math_round(-0.5).is_sign_negative()); assert!(math_round(0.25).is_sign_positive()); // A float too large to have a fractional part comes back untouched. assert_eq!(math_round(4_503_599_627_370_497.0), 4_503_599_627_370_497.0); // Non-finite values pass through, as they do in JavaScript. assert!(math_round(f64::NAN).is_nan()); assert_eq!(math_round(f64::INFINITY), f64::INFINITY); } }