From 2079c4f76c16bb49fab8a943cc27403fc9e480de Mon Sep 17 00:00:00 2001 From: George Roman Date: Wed, 14 Oct 2020 11:37:09 +0300 Subject: [PATCH] Fix JSON stringification for fractional numbers --- boa/src/builtins/json/tests.rs | 9 +++++++++ boa/src/value/mod.rs | 6 +++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/boa/src/builtins/json/tests.rs b/boa/src/builtins/json/tests.rs index 12b4fa0be32..0cf588d00cc 100644 --- a/boa/src/builtins/json/tests.rs +++ b/boa/src/builtins/json/tests.rs @@ -198,6 +198,15 @@ fn json_stringify_no_args() { assert_eq!(actual_no_args, expected); } +#[test] +fn json_stringify_fractional_numbers() { + let mut engine = Context::new(); + + let actual = forward(&mut engine, r#"JSON.stringify(Math.round(1.0))"#); + let expected = forward(&mut engine, r#""1""#); + assert_eq!(actual, expected); +} + #[test] fn json_parse_array_with_reviver() { let mut engine = Context::new(); diff --git a/boa/src/value/mod.rs b/boa/src/value/mod.rs index 132e6fec8b0..8a66dbdcf4c 100644 --- a/boa/src/value/mod.rs +++ b/boa/src/value/mod.rs @@ -227,9 +227,9 @@ impl Value { Self::Boolean(b) => Ok(JSONValue::Bool(b)), Self::Object(ref obj) => obj.to_json(interpreter), Self::String(ref str) => Ok(JSONValue::String(str.to_string())), - Self::Rational(num) => Ok(JSONNumber::from_f64(num) - .map(JSONValue::Number) - .unwrap_or(JSONValue::Null)), + Self::Rational(num) => Ok(JSONValue::Number( + JSONNumber::from_str(&Number::to_native_string(num)).unwrap(), + )), Self::Integer(val) => Ok(JSONValue::Number(JSONNumber::from(val))), Self::BigInt(_) => { Err(interpreter.construct_type_error("BigInt value can't be serialized in JSON"))