Crypto Decimal Precision: Handling Satoshis, Wei and Tiny Prices Without Float Errors
6 min read
Crypto decimal precision is a different problem from fiat precision. A dollar has two decimals, but one ether is 10^18 wei, and a binary floating-point number cannot hold that exactly. If you store balances as floats or parse API prices with parseFloat, you will eventually show a wrong amount or fail a reconciliation check.
The short answer: store every crypto amount as an integer count of its smallest unit, keep exchange rates as decimal strings, do the multiplication with integers or a decimal type, and round only once, at the edge, for display or invoicing. The rest of this article shows why and how, with code.
Why floats fail with crypto amounts
JavaScript numbers and the float types in most languages are IEEE 754 doubles. They have two limits that matter here.
First, they cannot represent most decimal fractions. The classic example is 0.1 + 0.2, which gives 0.30000000000000004. Crypto amounts like 0.00000001 are in the same category: they print fine but accumulate error when you add or multiply them.
Second, they have a limited integer range. A double is exact for whole numbers only up to 2^53 - 1, which is 9007199254740991. Beyond that, neighboring integers collapse together:
console.log(9007199254740993); // 9007199254740992
console.log(10 ** 18 + 1 === 10 ** 18); // true: one wei vanished
Bitcoin survives this: the total supply in satoshis (10^-8 BTC) is about 2.1 x 10^15, which fits under the limit. Ether in wei does not. Even 0.01 ETH is 10^16 wei, already past 2^53.
Very small prices cause a third, display-level problem. Some languages print tiny doubles in scientific notation, so 0.0000001 becomes "1e-7" in JavaScript. That string will break a database DECIMAL insert or a CSV import.
Know the smallest unit of each asset
Every asset defines a smallest indivisible unit. Your system should store amounts as integers in that unit and record the number of decimals next to the asset code.
| Asset | Smallest unit | Decimals |
|---|---|---|
| BTC | satoshi | 8 |
| LTC | litoshi | 8 |
| ETH | wei | 18 |
| SOL | lamport | 9 |
| XRP | drop | 6 |
Tokens are less uniform. A token's decimals are set by its contract and can differ between chains: a stablecoin may use 6 decimals on one network and 18 on another. Read the value from the contract or your own asset table instead of assuming it.
A workable storage schema looks like this:
asset: the code, for exampleBTCamount_units: an integer type big enough for the unit (aNUMERIC(78,0)or a string for 18-decimal assets)decimals: the asset's decimals, stored once per asset, not per row
If you do prefer storing decimals directly, use a NUMERIC column with enough scale, never FLOAT or DOUBLE.
Keep rates as strings until the last step
Exchange rates have the same problem in reverse. A rate for a low-priced asset can have many significant digits after the decimal point, and a rate for a high-priced asset has many before it. If your HTTP client auto-parses JSON numbers into doubles, you have already lost precision before your code runs.
GetRatesAPI returns rates and amounts as JSON strings and does not round results, so you can parse them with a decimal type of your choice. A rate response looks like this:
{"base":"BTC","quote":"USD","rate":"64250.12","as_of":"2026-01-02T10:00:00Z","status":"fresh","type":"direct"}
The numbers here are examples, not current prices. Crypto prices refresh every 10 seconds, and status tells you whether the observation is fresh or stale (crypto is stale after 1 minute). Check it before you act on the price.
Converting satoshis to cents with BigInt
Here is a JavaScript converter that never touches a float. It takes a BTC amount in satoshis, fetches the rate as a string, and returns US cents as a BigInt.
const API = "https://api.getratesapi.com";
function parseDecimal(str) {
if (!/^\d+(\.\d+)?$/.test(str)) throw new Error(`bad decimal: ${str}`);
const [whole, frac = ""] = str.split(".");
return { int: BigInt(whole + frac), scale: frac.length };
}
// amountUnits: BigInt in the base asset's smallest unit
// returns BigInt in the quote asset's smallest unit, rounded half up
function convertUnits(amountUnits, baseDecimals, quoteDecimals, rateStr) {
const r = parseDecimal(rateStr);
const num = amountUnits * r.int * 10n ** BigInt(quoteDecimals);
const den = 10n ** BigInt(baseDecimals + r.scale);
return (2n * num + den) / (2n * den); // round half up (positive values)
}
async function satsToUsdCents(sats) {
const res = await fetch(`${API}/v1/rates/BTC/USD`, {
headers: { Authorization: `ApiKey ${process.env.GETRATES_API_KEY}` },
});
const data = await res.json();
if (!res.ok) throw new Error(data.code); // match on "code" only
if (data.status !== "fresh") console.warn("stale rate", data.as_of);
return convertUnits(sats, 8, 2, data.rate);
}
Check the math with the example rate 64250.12. 150,000 sats is 0.0015 BTC, and 0.0015 x 64250.12 = 96.37518 dollars. The function computes 9637.518 cents and rounds half up to 9638, which is $96.38. No step used a float.
The same function works for wei: pass 18 as baseDecimals and a BigInt amount. Nothing about the algorithm changes, only the integer gets larger, and BigInt has no upper limit.
The same idea in Python
Python's Decimal makes this shorter. Set the context precision high enough for 18-decimal amounts, and quantize once at the end.
import os
import requests
from decimal import Decimal, localcontext, ROUND_HALF_UP
def wei_to_usd(wei: int) -> Decimal:
res = requests.get(
"https://api.getratesapi.com/v1/rates/ETH/USD",
headers={"Authorization": f"ApiKey {os.environ['GETRATES_API_KEY']}"},
timeout=10,
)
data = res.json()
if not res.ok:
raise RuntimeError(data["code"])
with localcontext() as ctx:
ctx.prec = 60
eth = Decimal(wei).scaleb(-18)
usd = eth * Decimal(data["rate"])
return usd.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
For a deeper walkthrough of rounding modes and why they matter for money, see our guide to currency conversion rounding without floating-point errors.
Let the API do the exact conversion
If you do not need to control the arithmetic yourself, the convert endpoint returns an exact converted_amount string for a given amount:
curl "https://api.getratesapi.com/v1/convert?from=BTC&to=USD&amount=0.0015" \
-H "Authorization: ApiKey $GETRATES_API_KEY"
The result is not rounded, so you still choose when and how to round. Send amounts as decimal strings built from your integer units (for example, format 150000 sats as 0.0015 with string manipulation, not by dividing a float).
Both the convert call and the single-rate call cost 1 request unit. Pairs that no market quotes directly are derived through USD, EUR or BTC, and the response says "type": "derived". A derived rate's as_of is its oldest input, so a BTC to JPY conversion is only as fresh as its slowest leg.
Round once, and round for the audience
Precision rules differ depending on where the number ends up.
- Fiat amounts you charge or invoice: round to the currency's minor unit (2 for USD, 0 for JPY). Our article on currency decimal places and minor units has the full table.
- Crypto amounts you display: show as many decimals as are useful, usually up to the asset's own decimals. Trim trailing zeros for readability, but never round the stored value.
- Tiny unit prices: a price like
0.00000123rounded to 2 decimals becomes0.00. Show a fixed number of significant digits instead, for example four. - Intermediate steps: do not round at all. Rounding each leg of a calculation compounds error.
A few habits prevent most bugs:
- Reject any amount that does not match a strict decimal pattern before it reaches your math.
- Never serialize a
BigIntorDecimalthroughNumber. In JavaScript, send amounts to your own API as strings. - Store the rate string, its
as_ofand the asset decimals next to every converted amount so you can reproduce it later. - Add a test with a value above 2^53 (such as 10^18 + 1 wei) and one with a very small rate, and make sure the output is exact.
Try it on your own assets
You can check which crypto codes are supported on the currencies page, and the asset catalog endpoints are free. To test the code above, create a free account, no credit card needed, and run a few calls in the dashboard playground. The free plan includes 500 request units a month, and you can compare larger plans on the pricing page.