From 7274fa4dd4b8666c88ae54d4874057ea915e030d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?D=C3=A1niel=20B=C3=A1tyai?= Date: Mon, 18 May 2020 18:39:00 +0200 Subject: [PATCH] Fix rounding in Number.prototype.toFixed (#3747) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #3741. JerryScript-DCO-1.0-Signed-off-by: Dániel Bátyai dbatyai@inf.u-szeged.hu --- .../ecma-builtin-number-prototype.c | 3 +- tests/jerry/number-prototype-to-fixed.js | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/jerry-core/ecma/builtin-objects/ecma-builtin-number-prototype.c b/jerry-core/ecma/builtin-objects/ecma-builtin-number-prototype.c index e913450ba..aaeecb675 100644 --- a/jerry-core/ecma/builtin-objects/ecma-builtin-number-prototype.c +++ b/jerry-core/ecma/builtin-objects/ecma-builtin-number-prototype.c @@ -673,6 +673,7 @@ ecma_builtin_number_prototype_object_to_fixed (ecma_number_t this_num, /**< this if (!ecma_number_is_zero (this_num)) { num_digits = ecma_number_to_binary_floating_point_number (this_num, digits, &exponent); + JERRY_ASSERT (exponent >= 0); } else { @@ -692,7 +693,7 @@ ecma_builtin_number_prototype_object_to_fixed (ecma_number_t this_num, /**< this /* 8. */ num_digits = ecma_builtin_number_prototype_helper_round (digits, - num_digits + 1, + num_digits + (lit_utf8_size_t) exponent, exponent + frac_digits, &exponent, ecma_number_is_zero (this_num)); diff --git a/tests/jerry/number-prototype-to-fixed.js b/tests/jerry/number-prototype-to-fixed.js index 67d5ed1bf..637296cd4 100644 --- a/tests/jerry/number-prototype-to-fixed.js +++ b/tests/jerry/number-prototype-to-fixed.js @@ -63,3 +63,35 @@ try { } catch (e) { assert(e instanceof RangeError) } + +assert ((0.5).toFixed(0) === "1"); +assert ((1.5).toFixed(0) === "2"); +assert ((12.5).toFixed(0) === "13"); +assert ((123.5).toFixed(0) === "124"); +assert ((1234.5).toFixed(0) === "1235"); +assert ((0.567).toFixed(0) === "1"); +assert ((1.567).toFixed(0) === "2"); +assert ((12.567).toFixed(0) === "13"); +assert ((123.567).toFixed(0) === "124"); +assert ((1234.567).toFixed(0) === "1235"); + +assert ((1.2567).toFixed(0) === "1"); +assert ((1.2567).toFixed(1) === "1.3"); +assert ((1.2567).toFixed(2) === "1.26"); +assert ((1.2567).toFixed(3) === "1.257"); +assert ((1.2567).toFixed(4) === "1.2567"); +assert ((1.2567).toFixed(5) === "1.25670"); + +assert ((12.3567).toFixed(0) === "12"); +assert ((12.3567).toFixed(1) === "12.4"); +assert ((12.3567).toFixed(2) === "12.36"); +assert ((12.3567).toFixed(3) === "12.357"); +assert ((12.3567).toFixed(4) === "12.3567"); +assert ((12.3567).toFixed(5) === "12.35670"); + +assert ((123.4567).toFixed(0) === "123"); +assert ((123.4567).toFixed(1) === "123.5"); +assert ((123.4567).toFixed(2) === "123.46"); +assert ((123.4567).toFixed(3) === "123.457"); +assert ((123.4567).toFixed(4) === "123.4567"); +assert ((123.4567).toFixed(5) === "123.45670");