Toolbox-XToolbox-X

Safely Add Numbers

Adds numbers safely, avoiding common floating-point arithmetic issues.

safeAdd

The safeAdd function adds multiple numbers or numeric strings together, avoiding common floating-point arithmetic issues (such as 0.1 + 0.2 !== 0.3) by scaling them to integers before performing the addition.

Function Signature

function safeAdd(...values: Numeric[]): number

Parameters

  • values (Numeric[]): A list of numbers or numeric strings to add.

Return Value

  • number: The sum of all the provided numbers, with floating-point inaccuracies mitigated.

Example Usage

playground.ts

Notes

  • This function addresses common floating-point addition errors by temporarily scaling numbers to integers, performing the addition, and then scaling back.
  • Non-numeric values are safely ignored during calculation.
  • Internally uses normalizeNumber, getDecimalPlaces, and roundNumber.

Warning

It does not handle numbers beyond Number.MAX_SAFE_INTEGER or Number.MIN_SAFE_INTEGER. May output incorrect results if the numbers are too large.

Aliases

The following alias can be used for the safeAdd function:

  • add

See Also

Last updated: Tue, Jun 16, 2026 07:49:37PM (UTC)

On this page