precise-add
v1.0.0
Published
This is to correctly add decimals by handling floating precision errors.
Maintainers
Readme
Precise Add
A lightweight JavaScript package that adds two numbers with precise decimal arithmetic, avoiding floating-point precision errors.
The Problem
JavaScript (and most programming languages) have floating-point precision issues:
0.1 + 0.2; // returns 0.30000000000000004 ❌
0.17 + 0.2; // returns 0.37000000000000005 ❌The Solution
const add = require("precise-add");
add(0.1, 0.2); // returns 0.3 ✅
add(0.17, 0.2); // returns 0.37 ✅Installation
npm install precise-addUsage
const add = require("precise-add");
// Basic usage
console.log(add(0.1, 0.2)); // 0.3
console.log(add(0.17, 0.2)); // 0.37
console.log(add(1.5, 2.3)); // 3.8
// Works with integers too
console.log(add(5, 10)); // 15
// Works with negative numbers
console.log(add(-0.1, 0.2)); // 0.1How It Works
The package converts decimal numbers to integers by multiplying by an appropriate power of 10, performs the addition, then converts back to decimal. This avoids the floating-point precision errors inherent in binary arithmetic.
API
add(a, b)
Adds two numbers with precise decimal arithmetic.
Parameters:
a(number): The first numberb(number): The second number
Returns:
- (number): The precise sum of a and b
Throws:
TypeError: If either argument is not a number or is NaN
Features
- ✅ Zero dependencies
- ✅ Lightweight (~1KB)
- ✅ Handles positive and negative numbers
- ✅ Handles integers and decimals
- ✅ Proper error handling
- ✅ Works with CommonJS and ES modules
Limitations
- Only handles addition (subtraction, multiplication, division coming soon!)
- Very large numbers may still have precision limits
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
ISC
Author
Rishi Prasad Aryal
Repository
https://github.com/rishi064/precise-add
