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[]): numberParameters
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, androundNumber.
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
sumNumbers- Sums up all numbers passed as arguments.getDecimalPlaces- Gets the number of decimal places in a number.roundNumber- Rounds a number to a specified number of decimal places.normalizeNumber- Normalizes a number or numeric string.
Last updated: Tue, Jun 16, 2026 07:49:37PM (UTC)
