Working with Big Numbers in JavaScript for Ethereum Applications
Ever tried moving money across an Ethereum app and suddenly noticed some weird decimal issues? Maybe you sent what looked like the right amount, but something seemed… off. That’s the reality of working with numbers in JavaScript for Ethereum.
Big numbers aren’t just large—they’re really large. And in blockchain, every single decimal matters. Tiny rounding errors could lead to financial disasters. The problem? JavaScript isn’t built to handle numbers at Ethereum’s scale natively. But there are ways around it.
Why JavaScript Struggles with Ethereum’s Big Numbers
JavaScript’s number type uses floating-point arithmetic, which is great for speed but terrible for precision. That’s a huge problem when dealing with cryptocurrency transactions, where even the smallest inaccuracy can cause real losses.
Ethereum Uses Huge Numbers—Bigger Than JavaScript Can Handle
Ethereum doesn’t just work with simple values like 10
or 0.5
. It deals with wei, the smallest unit of Ether, and there are 10^18 wei in a single ETH. That means even a small transaction could involve numbers that JavaScript simply can’t represent accurately.
The Risk of Rounding Errors in Ethereum Transactions
A tiny rounding error might not sound like a big deal—until you’re working with financial transactions. Imagine an app that wrongly calculates how much gas to send. If it underestimates, the transaction fails. If it overestimates, the user loses money. Both are bad.
How to Handle Big Numbers in JavaScript
Since JavaScript’s built-in Number
type isn’t reliable for Ethereum math, you’ll need something better.
Using BigInt for Integer Calculations
JavaScript introduced BigInt
, which can handle large integers without losing precision. It’s perfect for Ethereum because most calculations don’t involve decimals—just huge whole numbers.
Example:
let largeNumber = BigInt("1000000000000000000"); // 1 ETH in wei
console.log(largeNumber * 2n); // 2 ETH in wei
BigInt works great for whole numbers, but Ethereum transactions sometimes involve decimals. That’s where specialized libraries come in.
The Power of bn.js and BigNumber.js
Most Ethereum applications rely on bn.js or BigNumber.js to handle precision safely.
bn.js
: Optimized for performance, used by Ethereum’s core librariesBigNumber.js
: More user-friendly, great for financial calculations
Example using BigNumber.js
:
const BigNumber = require('bignumber.js');
let ethValue = new BigNumber("1.5").times("1000000000000000000"); // Convert ETH to wei
console.log(ethValue.toString()); // "1500000000000000000"
With libraries like these, calculations stay precise, and you avoid JavaScript’s floating-point pitfalls.
Converting Between Units Safely
Ethereum applications constantly convert between units—ETH, Gwei, and wei. If done wrong, users might send way too much or too little.
Using Ether.js for Unit Conversion
Ether.js makes these conversions easy and accurate.
const { ethers } = require("ethers");
console.log(ethers.utils.parseEther("1.5").toString()); // "1500000000000000000" (1.5 ETH to wei)
console.log(ethers.utils.formatEther("1500000000000000000")); // "1.5" (wei to ETH)
No weird rounding errors. Just safe, reliable conversions.
Common Mistakes with Unit Conversion
- Using division instead of a library: Dividing by
10^18
can introduce floating-point issues. - Forgetting wei is an integer: Don’t use decimals in wei values, or things will break.
- Relying on
Number
for big values: EvenparseInt
ortoFixed()
won’t save you from precision errors.
Handling Ethereum Transactions with Precision
Big numbers don’t just show up in calculations—they’re all over Ethereum smart contracts.
Reading and Writing Large Values from Contracts
When interacting with contracts, always use a BigNumber library to ensure correct values.
Example:
let contract = new ethers.Contract(contractAddress, contractABI, provider);
let balance = await contract.balanceOf(userAddress);
console.log(balance.toString()); // Always use .toString() to avoid unexpected behavior
Calculating Gas Fees Correctly
Gas fees fluctuate constantly, and getting them wrong can make transactions fail.
let gasPrice = await provider.getGasPrice();
console.log(ethers.utils.formatUnits(gasPrice, "gwei")); // Convert wei to Gwei safely
If you use Number()
, you risk losing precision and paying the wrong amount. Always work with libraries that handle big numbers properly.
Storing and Displaying Big Numbers
Storing Ethereum-related numbers in databases or showing them in user interfaces requires extra care.
Converting for Storage
Many apps store big numbers as strings to prevent precision loss.
Example JSON storage:
{
"userBalance": "123456789012345678901234567890"
}
This ensures numbers stay accurate, even if they’re huge.
Formatting Numbers for Display
Users don’t want to see huge, unreadable numbers. Formatting properly makes apps more user-friendly.
Example using ethers.js
:
console.log(ethers.utils.commify("1000000000000000000")); // "1,000,000,000,000,000,000"
This adds commas so users can read values easily.
Dealing with External Data Sources
Fetching Ethereum-related numbers from APIs or smart contracts requires caution.
Avoiding JavaScript’s Number
in API Responses
Many APIs return numbers as strings for a reason. Always handle them with a BigNumber library.
Bad approach:
let price = Number(apiResponse.price); // Might lose precision
Good approach:
let price = new BigNumber(apiResponse.price);
This keeps everything accurate, even when working with huge values.
Final Thoughts
Working with big numbers in JavaScript for Ethereum isn’t just about avoiding errors—it’s about making sure users don’t lose money. The wrong calculation could lead to failed transactions, wasted gas, or incorrect balances.
Using libraries like BigNumber.js
, bn.js
, and ethers.js
ensures precision, keeps calculations accurate, and makes conversions safe. Whether you’re handling balances, gas fees, or smart contract interactions, always assume JavaScript’s default number system isn’t enough.
Ethereum demands precision. JavaScript isn’t perfect, but with the right tools, you can make sure your numbers are.