LibJS: Fix parseFloat(-0) returning -0 instead of +0

The optimization that skips the string conversion for number values was
causing -0 to be returned as-is. This patch adds a check for this case.
This commit is contained in:
aplefull 2025-03-02 11:26:37 +01:00 committed by Tim Flynn
parent 61744322ad
commit 53cdb04ee8
Notes: github-actions[bot] 2025-03-02 16:31:28 +00:00
2 changed files with 27 additions and 2 deletions

View file

@ -247,8 +247,13 @@ JS_DEFINE_NATIVE_FUNCTION(GlobalObject::parse_float)
auto string = vm.argument(0);
// OPTIMIZATION: We can skip the number-to-string-to-number round trip when the value is already a number.
if (string.is_number())
if (string.is_number()) {
// Special case for negative zero - it should become positive zero
if (string.is_negative_zero())
return Value(0);
return string;
}
// 1. Let inputString be ? ToString(string).
auto input_string = TRY(string.to_string(vm));

View file

@ -1,6 +1,16 @@
// This is necessary because we can't simply check if 0 is negative using equality,
// since -0 === 0 evaluates to true.
// test262 checks for negative zero in a similar way here:
// https://github.com/tc39/test262/blob/main/test/built-ins/parseFloat/S15.1.2.3_A1_T2.js
function isZeroNegative(x) {
const isZero = x === 0;
const isNegative = 1 / x === Number.NEGATIVE_INFINITY;
return isZero && isNegative;
}
test("parsing numbers", () => {
[
[0, 0],
[1, 1],
[0.23, 0.23],
[1.23, 1.23],
@ -14,6 +24,16 @@ test("parsing numbers", () => {
});
});
test("parsing zero", () => {
expect(isZeroNegative(parseFloat("0"))).toBeFalse();
expect(isZeroNegative(parseFloat("+0"))).toBeFalse();
expect(isZeroNegative(parseFloat("-0"))).toBeTrue();
expect(isZeroNegative(parseFloat(0))).toBeFalse();
expect(isZeroNegative(parseFloat(+0))).toBeFalse();
expect(isZeroNegative(parseFloat(-0))).toBeFalse();
});
test("parsing strings", () => {
[
["0", 0],