Skip to content

Round exported values below about 1e-298 instead of returning NaN (HF-555) - #1837

Open
marcin-kordas-hoc wants to merge 5 commits into
developfrom
fix/hf-555-tiny-value-rounding
Open

marcin-kordas-hoc wants to merge 5 commits into
developfrom
fix/hf-555-tiny-value-rounding

Conversation

@marcin-kordas-hoc

@marcin-kordas-hoc marcin-kordas-hoc commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Context

The PR fixes NaN returned for cell values smaller than about 1e-298 when smartRounding is on (the default).

  • Why: the exporter rounds each number with the multiplier 10 ** (precisionRounding - magnitude). Below about 1e-298 that multiplier is Infinity, so getCellValue() returned Infinity / Infinity, which is NaN.
  • What changed: hyperformula/src/Exporter.ts: when the multiplier overflows, the value is rounded with toPrecision to the same number of significant digits instead.
  • Result: tiny values are rounded like any other number. All other values are exported bit for bit as before.
Cell Before After
=1e-298 1e-298 1e-298
=2e-299 NaN 2e-299
=-1e-300 NaN -1e-300
=1.23456789012345e-301 NaN 1.2345678901e-301
=1e-200*1e-120 NaN 1e-320

How did you test your changes?

  • Paired branch fix/hf-555-tiny-value-rounding in hyperformula-tests: 5 new tests in unit/CellValueExporter.spec.ts. All 5 fail on develop and pass on this branch.
  • Compared exported values on develop and on this branch for 41,970 inputs. They cover magnitudes from 1e-330 to the largest double, both signs, and precisionRounding 0, 4, 10, 15 and 300. 34,821 are identical (Object.is), and the 7,141 that were NaN are now numbers. The other 8 are Number.MAX_VALUE inputs that export as ±Infinity on both branches.
  • npx jest on the whole suite, eslint and tsc --noEmit on the changed files.

AI assistance

Claude Code co-authored 3 of the 3 non-merge commits on this branch and 2 of the 2 on the paired hyperformula-tests branch (handsontable/hyperformula-tests#101), as the Co-Authored-By: Claude trailers record. Those commits touch hyperformula/src/Exporter.ts and CHANGELOG.md here, and unit/CellValueExporter.spec.ts in the tests branch.

Compatibility with Excel and Google Sheets

Not applicable: the change only affects rounding on export. The exported value now matches the value computed with smartRounding off, rounded to precisionRounding significant digits.

Formula Excel Google Sheets HyperFormula
Not applicable

Public API changes

None.

Out of scope and follow-ups

  • Number.MAX_VALUE exports as Infinity with smartRounding on, because rounding it up exceeds the largest double. This is unchanged here.
  • ROUND, ROUNDUP and ROUNDDOWN return #NUM! when the number of places is above 308, for example =ROUND(1.5, 400). They use the same multiplier pattern but are a separate change.
  • Just above the overflow point, the exported value still differs from the one computed with smartRounding off: =1e-290 exports as 9.999999999999999e-291, and as 1e-290 with smartRounding off.

Types of changes

  • Breaking change (existing functionality no longer works as before) – agreed with the maintainers
  • New feature or improvement (a non-breaking change that adds functionality)
  • Bug fix (a non-breaking change that fixes an issue)
  • Additional language file, or a change to an existing language file (translations)
  • Change to the documentation

Related issues

  1. HF-555

Checklist

🤖 Generated with Claude Code


Note

Low Risk
Localized bug fix in export-time rounding with no API changes; only affects previously broken tiny numeric exports.

Overview
Fixes exported cell values turning into NaN when smartRounding is enabled (the default) and the number is smaller than about 1e-298.

The exporter’s cellValueRounding path used a scale factor 10 ** (precisionRounding - magnitude) that overflows to Infinity for extremely small magnitudes, so Math.round produced Infinity / Infinity → NaN. When that multiplier is infinite, rounding now falls back to Number(value.toPrecision(...)) with the same effective significant-digit limit (capped at 100). Normal-sized numbers still use the existing multiply-and-round logic unchanged.

CHANGELOG documents the fix under Unreleased → Fixed.

Reviewed by Cursor Bugbot for commit 3f2eee1. Bugbot is set up for automated code reviews on this repo. Configure here.

marcin-kordas-hoc and others added 3 commits October 22, 2026 05:37
… NaN

With smartRounding on, the rounding multiplier 10 ** (precisionRounding - magnitude) overflowed
to Infinity for tiny values, so the exported value was Infinity / Infinity = NaN. When the
multiplier overflows, the value is now rounded with toPrecision instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
hyperformula-docs 9460640 Commit Preview URL

Branch Preview URL
Nov 25 2026, 09:47 AM

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Performance comparison of head (9460640) vs base (2aaab7d)

                                     testName |    base |    head | change
--------------------------------------------------------------------------
                                      Sheet A |  511.95 |  512.35 | +0.08%
                                      Sheet B |  170.57 |  165.05 | -3.24%
                                      Sheet T |  151.02 |  149.74 | -0.85%
                                Column ranges |  491.21 |  480.67 | -2.15%
                                Sorted lookup | 14722.4 | 15203.4 | +3.27%
Sheet A:  change value, add/remove row/column |   17.37 |   16.46 | -5.24%
 Sheet B: change value, add/remove row/column |  144.23 |  137.88 | -4.40%
                   Column ranges - add column |  163.42 |  161.81 | -0.99%
                Column ranges - without batch |  465.12 |  482.64 | +3.77%
                        Column ranges - batch |  115.56 |  117.22 | +1.44%

@Tobiadefami Tobiadefami left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hyperformula/src/Exporter.ts:136

Suggestion: the guard catches a multiplier that overflows, but not a product that overflows, so ordinary values still export as Infinity once precisionRounding is 308 or more:

const exported = (v, precisionRounding) =>
  HyperFormula.buildFromArray([[v]], { precisionRounding }).getCellValue({ sheet: 0, row: 0, col: 0 })

exported(50, 308)      // Infinity, should be 50
exported(123.456, 309) // Infinity, should be 123.456
exported(5, 309)       // 5: the multiplier overflows, so the new path handles it

This was already the case before this PR, but it's in the same function. Checking the product covers both cases:

if (!Number.isFinite(value * placesMultiplier)) {

Could we use that and add a test for 50 with precisionRounding: 308? If you'd rather leave it, could you list it under the follow-ups in the description?

@handsontable-pr-review handsontable-pr-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Medium risk: Touches the export/rounding path used by every getCellValue with smartRounding enabled, but the new branch only triggers where the old code already returned NaN, so blast radius is limited to previously-broken tiny values.

Full review: no issues found.

Want a deeper review? Comment /review improve on its own line: a full review of the latest commit with an extra fix-oriented pass (about 2x the cost).

marcin-kordas-hoc added a commit that referenced this pull request Nov 23, 2026
…HF-423, HF-422, HF-426) (#1800)

### Context
The PR adds the statistical functions `KURT`, `MODE.SNGL` with its alias
`MODE`, `PERCENTRANK.EXC` and `TRIMMEAN`, and fixes a stack overflow
that `KURT` shares with ten existing functions.

- **Why:** HyperFormula has none of the four functions, so these
formulas give `#NAME?`. And `AVEDEV`, `DEVSQ`, `GCD`, `GEOMEAN`,
`HARMEAN`, `LCM`, `MEDIAN`, `NPV`, `SKEW` and `SKEW.P` throw
`RangeError: Maximum call stack size exceeded` for a range of about
125,000 cells or more, so the whole engine fails to build.
- **What changed:**
- `StatisticalAggregationPlugin.ts`: `KURT`, `MODE.SNGL` (alias `MODE`)
and `TRIMMEAN`.
- `KURT(number1, ...)`: sample excess kurtosis; `#DIV/0!` with fewer
than 4 numbers or when all are equal.
- `MODE.SNGL(number1, ...)`: the most frequent number, the first one on
a tie; `#N/A` when nothing repeats. Text and booleans are ignored; an
empty argument, or a reference to an empty cell passed as an argument,
is `#VALUE!`, as in Excel.
- `TRIMMEAN(array, percent)`: the mean without the given fraction of
values, split between both ends. An error in the range is returned
before `percent` is checked, as in Excel.
- `PercentilePlugin.ts`: `PERCENTRANK.EXC(array, x, [significance])`,
the rank of `x` between 0 and 1, exclusive, interpolated between
neighbours. An empty `significance` takes the default of 3. Errors come
in Excel's order: an error in the range, then `x` outside the values
(`#N/A`), then `significance` (`#NUM!`).
- `ArithmeticHelper.ts`: `manyToNumbers` appends the values of a range
in a loop instead of `push(...arr)`, which passed every value as a call
argument and exceeded the call stack.
  - `error-message.ts`: one message for `KURT` with too few values.
- `categories/statistical.ts`, `functionCapabilities.ts` and 17 language
files: catalogue entries, license capability entries and names.
- `list-of-differences.md`: a row for `TRIMMEAN` with numeric text as
`percent`.
- `CHANGELOG.md`: one `Added` entry for the four functions and one
`Fixed` entry for the ten.
- **Result:** the four functions and `MODE` evaluate in every language
pack except `ruRU`, where the parser accepts no Cyrillic function name
(`=СУММ(1,2)` is a parsing error on `develop` as well), and the eleven
functions read a range of 150,000 values.

`KURT` follows Excel's floating-point arithmetic: it uses the plain mean
and standard deviation, not the compensated sums of `DEVSQ`, `VAR.S` and
`STDEV.S`, so it gives Excel's result where rounding decides it.
`=KURT(A1:A6)` over six cells of 0.1 is -3.33333333333333 in Excel and
in HyperFormula, and `KURT` of 1, 2, 3 and 5 scaled by 1e155 or by
1e-170 is `#DIV/0!` in both. Excel's `DEVSQ` of the six cells is
1.15555796663234E-33, where HyperFormula's `DEVSQ` returns 0.

Translations come from the Excel 2013 function translation table listed
in `hyperformula/dev-docs/I18N.md`, except two in `ptPT`. The table
lists European Portuguese names, while the `ptPT` pack uses the
Brazilian ones (`SOMASE`, `MODO`), so `MODE.SNGL` is `MODO.ÚNICO` and
`PERCENTRANK.EXC` is `ORDEM.PORCENTUAL.EXC`, as on Microsoft's pt-BR
function pages. Apart from those two, the function pages were not
checked one by one. `idID`, which the table does not cover, keeps the
English names, and so does any name that would duplicate another
function in the same language.

### How did you test your changes?
Paired tests: `feat/hf-stats-kurt-mode-trimmean-percentrank-exc` in
`hyperformula-tests` (handsontable/hyperformula-tests#86).

- `npx jest` on the 4 new specs: 206 passed, one assertion per case.
With the error-order and empty-argument changes reverted, 13 of them
fail; with the five translated names they call misspelled, the 5
language cases fail; with the two `ptPT` names back to the European
ones, the 2 `ptPT` cases fail. `PERCENTRANK.EXC` rounds the scaled
quotient to 15 significant digits before the truncation; without that,
the 4 cases whose result is exactly a truncation step fail, and with the
earlier fixed `1e-9` the 2 at significance 9 fail
(`=PERCENTRANK.EXC({1,2},1.2,9)` gave 0.399999999; Excel gives 0.4 at
significance 3 to 15).
- A case with a 150,000-value range in the specs of `KURT` and the ten
fixed functions, against values computed independently: all 11 pass;
with `push(...arr)` restored, all 11 fail with `RangeError`.
- On `develop`, `buildFromArray` throws for each of the ten functions
over 160,000 cells; the smallest range that throws holds between 124,348
and 124,652 values (Node 24).
- Differential against this branch before the review changes, on 936
formulas (the edge cases below and `SEQUENCE` sweeps of the functions
that read through `manyToNumbers`): no result turns from a number into
an error except `=MODE.SNGL(1,1,)` and `=MODE.SNGL(1,1,E9)`, which are
now `#VALUE!` as in Excel.
- Full `npx jest` with the paired tests at this head: 527 suites passed;
7308 tests passed, 3 skipped. `tsc --noEmit`: 0 errors. `npx eslint` on
the changed `.ts` files: 0 errors.

### AI assistance
Claude Code (Claude Opus and Claude Sonnet) wrote the code, the tests
and the documentation changes in this pull request and in
hyperformula-tests#86. Every commit on both branches, other than merges,
carries its co-author line.

### Compatibility with Excel and Google Sheets
Measured in Excel Online. Numbers are compared with a relative tolerance
of 1e-9, because HyperFormula rounds results to about 11 significant
digits. Google Sheets was not checked.

- 76 formulas that call the four functions, from the review of this PR:
66 give Excel's result. The 10 others are in the classes listed below,
except `=TRIMMEAN({1,2,3},"0.5")`, which is `#VALUE!` in Excel and 2
here.
- 784 edge cases (empty, text, boolean, error, magnitude, array and
range inputs for each argument): 100 differ, all in input classes that
existing functions such as `SKEW`, `DEVSQ`, `MEDIAN` and
`PERCENTILE.INC` share, measured the same way:
- 24: a range or computed array where one number is expected, with array
arithmetic off (Excel intersects or spills);
- 20: text before an error argument (Excel returns `#VALUE!`,
HyperFormula the error);
- 12: uppercase exponents such as `1E5`, which do not parse before
#1835; 12 more are `1e308` formulas that Excel does not accept;
- 9: `""` as a number (Excel `#VALUE!`, HyperFormula 0); 8: a 1x1 text
array (Excel ignores it, HyperFormula `#VALUE!`);
- 7: a reference to an empty cell passed as an argument (`KURT` counts
it as 0 where Excel skips it, and `MODE.SNGL` returns the error of a
later argument where Excel returns `#VALUE!`);
- 6: a single value where a range is expected; 1: `significance` of
`1e21` (Excel `#DIV/0!`; at this head HyperFormula also returns
`#DIV/0!`, for any `significance` of 309 or more); 1: a result below
`1e-298` (HF-555, #1837).
- Found in review, not in the edge set: a reference to a cell holding
text, `TRUE` or numeric text passed as its own argument. With A1:D1 = 1,
2, 3, 10, `=KURT(A1:D1,E1)` gives `#VALUE!`, 4.0280698323 and
1.7837435675 for E1 = `x`, `TRUE` and `="5"`, where Excel skips the cell
and gives 3.228 for all three. `SKEW` does the same on `develop`.

| Formula | Excel | Google Sheets | HyperFormula |
|---|---|---|---|
| `=KURT(1,2,3,10)` | 3.228 | Not checked | 3.228 |
| `=KURT(A1:A6)`, six cells of 0.1 | -3.33333333333333 | Not checked |
-3.3333333333 |
| `=MODE.SNGL(3,3,1,1)` | 3 | Not checked | 3 |
| `=MODE.SNGL(0,,1)` | `#VALUE!` | Not checked | `#VALUE!` |
| `=PERCENTRANK.EXC({1,2,3},2,)` | 0.5 | Not checked | 0.5 |
| `=PERCENTRANK.EXC(A1:C1,2,0)`, A1:C1 = 1, `=1/0`, 3 | `#DIV/0!` | Not
checked | `#DIV/0!` |
| `=PERCENTRANK.EXC({2},2,0)` | 1 | Not checked | 1 |
| `=TRIMMEAN(A1:C1,2)`, A1:C1 = 1, `=1/0`, 3 | `#DIV/0!` | Not checked |
`#DIV/0!` |
| `=TRIMMEAN(A1:K1,0.5)`, 11 values | 3.71428571428571 | Not checked |
3.7142857143 |

### Public API changes
None. Five new built-in function names (four functions and the `MODE`
alias).

### Out of scope and follow-ups
- The input classes listed under Compatibility apply to the existing
functions as well; changing them is an engine-wide change, not part of
this PR.
- `=TRIMMEAN({1,2,3},"0.5")`: Excel rejects numeric text as `percent`;
HyperFormula reads it as 0.5.
- `GEOMEAN` over 160,000 values no longer throws but returns `#NUM!`,
because the product of the values overflows.
- `IMSUM` and `IMPRODUCT` read ranges through
`coerceComplexExactRanges`, which still uses `push(...arr)`, and
`TEXTJOIN` spreads its texts the same way: `=IMSUM(A1:D40000)` and
`=TEXTJOIN("",TRUE(),A1:D40000)` throw `RangeError` on `develop` and
here.
- `SKEW` and `SKEW.P` return 0 when the variance overflows, for example
over 1e155, 2e155, 3e155 and 5e155, where `KURT` and Excel return
`#DIV/0!`.

### Types of changes
- [ ] Breaking change (existing functionality no longer works as before)
– agreed with the maintainers
- [x] New feature or improvement (a non-breaking change that adds
functionality)
- [x] Bug fix (a non-breaking change that fixes an issue)
- [x] Additional language file, or a change to an existing language file
(translations)
- [ ] Change to the documentation

### Related issues
1. HF-427 (`KURT`), HF-423 (`MODE.SNGL`), HF-422 (`PERCENTRANK.EXC`),
HF-426 (`TRIMMEAN`)

### Checklist
- [x] My pull request meets the [Definition of
Done](https://github.com/handsontable/hyperformula/blob/develop/dev-docs/DEFINITION-OF-DONE.md).
External contributors: see also [Contributing to
HyperFormula](https://handsontable.com/docs/hyperformula/guide/contributing.html).
- [ ] I have signed the [Contributor License
Agreement](https://goo.gl/forms/yuutGuN0RjsikVpM2).
- [ ] I read my own diff end to end before requesting a review.
- [x] I added a
[CHANGELOG.md](https://github.com/handsontable/hyperformula/blob/develop/CHANGELOG.md)
entry, written by [the changelog
rules](https://github.com/handsontable/hyperformula/blob/develop/dev-docs/DOC-STANDARDS.md#the-changelog)
– or none is needed (docs, tests or tooling only).
- [x] I updated the documentation and JSDoc to match the change.
- [ ] Breaking change only: I added a section to the migration guide.
- [x] I updated the `dev-docs/` pages this change affects – or none
needed it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> New formula behavior plus a core range-coercion change affects many
statistical functions on very large inputs; scope is broad but behavior
is additive with a targeted performance/stability fix.
> 
> **Overview**
> Adds four Excel-style statistical functions—**`KURT`**,
**`MODE.SNGL`** (with **`MODE`** alias), **`PERCENTRANK.EXC`**, and
**`TRIMMEAN`**—in the statistical plugins, with catalogue entries,
license capabilities, and translations across language packs.
> 
> **`PERCENTRANK.EXC`** ranks a value in a range (exclusive method,
optional decimal truncation) with Excel-like error ordering.
**`TRIMMEAN`** averages a range after trimming ends by percent.
**`KURT`** and **`MODE.SNGL`** follow the usual aggregation patterns
(minimum sample size, tie/frequency rules).
> 
> **`ArithmeticHelper`** no longer uses `push(...arr)` when flattening
large ranges; it appends in a loop instead, fixing **stack overflows**
when building formulas over ~125k cells for these functions and several
existing ones (`AVEDEV`, `DEVSQ`, `GCD`, `GEOMEAN`, `HARMEAN`, `LCM`,
`MEDIAN`, `NPV`, `SKEW`, `SKEW.P`).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
847f4ff. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>

@Tobiadefami Tobiadefami left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fallback works: values below about 1e-298 now export as numbers, and every new test fails on develop. Blocking: the AI assistance section (see handsontable/hyperformula-tests#101).


hyperformula/src/Exporter.ts:132

suggestion: The description says the exported value now matches the one computed with smartRounding off, but just above the overflow point it doesn't: =1e-290 exports as 9.999999999999999e-291, and as 1e-290 with smartRounding off. The multiplier (1e300) is still finite there, so the multiply-and-divide path runs. Could "Out of scope and follow-ups" list it?

@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 97.75%. Comparing base (2aaab7d) to head (9460640).
⚠️ Report is 2 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop    #1837   +/-   ##
========================================
  Coverage    97.75%   97.75%           
========================================
  Files          212      212           
  Lines        18817    18820    +3     
  Branches      4436     4404   -32     
========================================
+ Hits         18394    18397    +3     
+ Misses         423      415    -8     
- Partials         0        8    +8     
Files with missing lines Coverage Δ
hyperformula/src/Exporter.ts 89.74% <100.00%> (+0.41%) ⬆️

... and 5 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants