mirror of
https://github.com/n8n-io/n8n.git
synced 2026-09-19 09:51:59 +08:00
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:
co-authored by
n8n-cat-bot[bot]
Claude Opus 4.8
parent
4b807b7c49
commit
08052c19eb
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user