fix: Handle exponential-notation numbers in smartDecimal (#35967)

Co-authored-by: n8n-cat-bot[bot] <n8n-cat-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
n8n-cat-bot[bot]
2026-08-11 11:01:16 +00:00
committed by GitHub
co-authored by n8n-cat-bot[bot] Claude Opus 4.8
parent 4b807b7c49
commit 08052c19eb
2 changed files with 21 additions and 2 deletions
@@ -32,4 +32,21 @@ describe('smartDecimal', () => {
it('should round to two decimal if it is smaller than the given one', () => {
expect(smartDecimal(42.56, 3)).toBe(42.56);
});
it('should round exponential-notation numbers to zero at the default decimals', () => {
// `0.0000001` stringifies to `"1e-7"` (no decimal point)
expect(smartDecimal(0.0000001)).toBe(0);
});
it('should round exponential-notation numbers correctly at higher precision', () => {
expect(smartDecimal(0.0000001, 8)).toBe(0.0000001);
});
it('should round negative exponential-notation numbers to zero', () => {
const result = smartDecimal(-0.0000001);
// `Number((-0.0000001).toFixed(2))` yields `-0`. `toBe(0)` uses `Object.is`
// and would fail on `-0`, so assert value equality with `===`, which treats
// `-0 === 0` as `true` — the -0 pitfall.
expect(result === 0).toBe(true);
});
});
@@ -4,8 +4,10 @@ export const smartDecimal = (value: number, decimals = 2): number => {
return value;
}
// Check if it has only one decimal place
if (value.toString().split('.')[1].length <= decimals) {
// Check if it has only one decimal place. Exponential-notation numbers
// (e.g. `0.0000001` → `"1e-7"`) have no `.`, so fall through to rounding.
const decimalPart = value.toString().split('.')[1];
if (decimalPart !== undefined && decimalPart.length <= decimals) {
return value;
}