util: fix numericSeparator with negative fractional numbers

Fix util.inspect() formatting bug where negative fractional numbers
between -1 and 0 lost their minus sign when numericSeparator was true.
Fixed formatNumber function to preserve sign by using original string
representation. Also corrected test expectations for scientific notation
to not apply numeric separators.
Fixes: https://github.com/nodejs/node/issues/59376

PR-URL: https://github.com/nodejs/node/pull/59379
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
sangwook authored and Richard Lau committed 2025-09-20 06:17:30 +00:00
1 parent 658c31d60c
commit f660943471
2 files changed
+35 -9

No files matched your search

+14 -9
View File
@@ -1851,23 +1851,28 @@ function formatNumber(fn, number, numericSeparator) {
}
return fn(`${number}`, 'number');
}
const numberString = String(number);
const integer = MathTrunc(number);
const string = String(integer);
if (integer === number) {
if (!NumberIsFinite(number) || StringPrototypeIncludes(string, 'e')) {
return fn(string, 'number');
if (!NumberIsFinite(number) || StringPrototypeIncludes(numberString, 'e')) {
return fn(numberString, 'number');
}
return fn(`${addNumericSeparator(string)}`, 'number');
return fn(addNumericSeparator(numberString), 'number');
}
if (NumberIsNaN(number)) {
return fn(string, 'number');
return fn(numberString, 'number');
}
const decimalIndex = StringPrototypeIndexOf(numberString, '.');
const integerPart = StringPrototypeSlice(numberString, 0, decimalIndex);
const fractionalPart = StringPrototypeSlice(numberString, decimalIndex + 1);
return fn(`${
addNumericSeparator(string)
addNumericSeparator(integerPart)
}.${
addNumericSeparatorEnd(
StringPrototypeSlice(String(number), string.length + 1),
)
addNumericSeparatorEnd(fractionalPart)
}`, 'number');
}
+21
View File
@@ -3484,6 +3484,27 @@ assert.strictEqual(
util.inspect(-123456789.12345678, { numericSeparator: true }),
'-123_456_789.123_456_78'
);
// Regression test for https://github.com/nodejs/node/issues/59376
// numericSeparator should work correctly for negative fractional numbers
{
// Test the exact values from the GitHub issue
const values = [0.1234, -0.12, -0.123, -0.1234, -1.234];
assert.strictEqual(
util.inspect(values, { numericSeparator: true }),
'[ 0.123_4, -0.12, -0.123, -0.123_4, -1.234 ]'
);
// Test individual negative fractional numbers between -1 and 0
assert.strictEqual(
util.inspect(-0.1234, { numericSeparator: true }),
'-0.123_4'
);
assert.strictEqual(
util.inspect(-0.12345, { numericSeparator: true }),
'-0.123_45'
);
}
}
// Regression test for https://github.com/nodejs/node/issues/41244