JavaScript Reference ยท Math
Math.sumPrecise()
Reference for JavaScript Math.sumPrecise(): add an iterable of numbers with a single rounding step, avoid floating-point drift, and detect support safely.
Math.sumPrecise() adds up the numbers in an iterable and returns the sum rounded only once, at the very end. A normal loop or reduce() rounds after every addition, so small errors pile up, and large values can swallow small ones completely. sumPrecise() works out the exact mathematical sum first and then gives you the closest double-precision number.
This is a recent addition to the language, so it is not available everywhere yet. Always test for it before you call it, and keep a fallback for environments that lack it.
if (typeof Math.sumPrecise === "function") { Math.sumPrecise([0.1, 0.2, 0.3]); // 0.6 }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Math.sumPrecise(items)
| Name | Description |
|---|---|
items |
An iterable (array, set, generator, ...) that produces only Number values. |
Return value: the exact sum of all values, rounded to the nearest representable number. An empty iterable gives -0. A single NaN, or both Infinity and -Infinity, gives NaN. Only Infinity values give Infinity (likewise for -Infinity).
Exceptions: a TypeError if the argument is not iterable, or if any element is not a Number (strings, BigInt values and null are not converted).
Usage notes
- It takes one iterable, not many arguments. Write
Math.sumPrecise([a, b, c]), notMath.sumPrecise(a, b, c). This differs fromMath.max(), and it avoids the argument-count limit for huge lists. - No coercion.
Math.sumPrecise(["1", "2"])throws. Convert first, for example withmap(Number). - It is exact, not magic. The inputs are already doubles, so
0.1is still slightly off from one tenth. What you gain is that no further error is added while summing. - Large intermediate values do not overflow unless the true final sum does not fit in a double.
- Empty input returns
-0, which prints as-0in some consoles and compares equal to0. UseObject.is()if you must tell them apart. - For money, prefer whole cents stored as integers over decimal fractions, whether or not you use this method.
- Performance: it may be slower than a plain loop. Use it where accuracy matters (statistics, accounting totals, scientific data), not in hot paths where small drift is fine.
Browser support
Math.sumPrecise() is a newer feature and is limited or missing in some browsers and runtimes, so check a compatibility table and feature-detect as shown above.
Related
Math.max(),Math.round()- floating-point numbers
- Lessons: Numbers, Math