dnum provides a small set of utilities designed for the manipulation of large numbers. It provides useful features for everyday apps, such as formatting and math functions. Numbers are represented as a pair composed of a value (BigInt) and a decimal precision. This structure allows to maintain the number precision while offering a great flexibility.
type Dnum = [value: bigint, decimals: number];
Usage
import * as dn from "dnum";
let a = dn.from(2, 18); // the number 2 followed by 18 decimals
let a = [2000000000000000000n, 18]; // equivalent to the previous line
let b = dn.from("870983127.93887"); // dn.from() can parse strings, numbers, bigint and more
let c = dn.multiply(a, b); // returns [1741966255877740000000000000n, 18]
console.log(
dn.format(a), // "2"
dn.format(b, 2), // "870,983,127.94"
dn.format(c, 2), // "1,741,966,255.88"
dn.format(b, { compact: true }), // "1.7B"
);
Install
npm install --save dnum
pnpm add dnum
bun add dnum
TL;DR
dnum might be a good option for your project if:
- Your numbers are represented as value + decimals pairs.
- You need to format large numbers for UI purposes.
- You want to keep your big numbers library small.
- You want a simple, straightforward data structure.
Example
dnum can be used to perform math operations on currency values. Let’s consider a scenario where you have the price of a specific token known as TKN, expressed in ETH, received as a string to prevent potential precision issues:
let tknPriceInEth = "17.30624293209842";
And you received the price of 1 ETH in USD from a different source, as a JavaScript number:
let ethPriceInUsd = 1002.37;
Finally, your app has a specific quantity of TKN to be displayed, represented as a BigInt with an implied 18 decimals precision:
let tknQuantity = 1401385000000000000000n; // 1401.385 (18 decimals precision)
You want to display the USD value of tknQuantity. This would normally require to:
- Parse the numbers correctly (without using
parseInt() / parseFloat() to avoid precision loss).
- Convert everything into BigInt values with an identical decimals precision.
- Multiply the numbers.
- Convert the resulting BigInt into a string and format it for display purposes, without
Intl.NumberFormat since it would cause precision loss.
dnum can do all of this for you:
let tknPriceInEth = "17.30624293209842";
let ethPriceInUsd = 1002.37;
let tknQuantity = 1401385000000000000000n; // 1401.385 (18 decimals precision)
// dnum function parameters accept various ways to represent decimal numbers.
let tknPriceInUsd = dnum.multiply(tknPriceInEth, ethPriceInUsd);
let tknQuantityInUsd = dnum.multiply(
// Here we only attach the 18 decimals precision with the bigint value,
// which corresponds to the Dnum type: [value: bigint, decimals: number].
// You can pass this structure anywhere dnum expects a value, and this is
// also what most dnum functions return.
[tknQuantity, 18],
tknPriceInUsd,
);
// We can now format the obtained result, rounding its decimals to 2 digits:
dnum.format(tknQuantityInUsd, 2); // $24,310,188.17
You can play with this example on CodeSandbox.
Contract calls
Here is how to display a USDC balance and send 0.001 USDC using viem. This example assumes the clients and addresses are already configured.
import * as dn from "dnum";
import { erc20Abi } from "viem";
// Read the balance and attach the token’s decimals (6 for USDC).
let balanceValue = await publicClient.readContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "balanceOf",
args: [ownerAddress],
});
let balance: dn.Dnum = [balanceValue, 6];
console.log(dn.format(balance));
// Send 0.001 USDC using the bigint from the Dnum.
let amount = dn.from("0.001", 6); // [1000n, 6]
await walletClient.writeContract({
address: tokenAddress,
abi: erc20Abi,
functionName: "transfer",
args: [recipientAddress, amount[0]],
});
API
Types
type Dnum = [value: bigint, decimals: number];
type Numberish = string | number | bigint | Dnum;
format(value, options)
Formats the number for display purposes.
| Name |
Description |
Type |
value |
The value to format. |
Dnum |
options.digits |
Number of fractional digits to display. Setting options to a number acts as an alias for this option (see example below). Defaults to the Dnum decimals unless significantDigits is set. |
number |
options.significantDigits |
Round to this many significant digits. With digits, use whichever precision preserves more detail. Must be a positive safe integer. Cannot be combined with compact: true. |
number |
options.compact |
Compact formatting (e.g. “1,000” becomes “1K”). |
boolean |
options.trailingZeros |
Add trailing zeros if any, following the number of digits. |
boolean |
options.locale |
The locale used to format the number. |
string |
options.decimalsRounding |
Method used to round to digits decimals (defaults to "ROUND_HALF"). |
"ROUND_HALF" | "ROUND_UP" | "ROUND_DOWN" |
options.signDisplay |
When to display the sign for the number. Follows the same rules as Intl.NumberFormat. Defaults to "auto". |
"auto" | "always" | "exceptZero" | "negative" | "never" |
| returns |
Formatted string. |
string |
Example
let amount = [123456789000000000000000n, 18];
// If no digits are provided, the digits correspond to the decimals
dnum.format(amount); // 123,456.789
// options.digits
dnum.format(amount, { digits: 2 }); // 123,456.79
dnum.format(amount, 2); // 123,456.79 (alias for { digits: 2 })
// options.compact
dnum.format(amount, { compact: true }); // 123K
// options.trailingZeros
dnum.format(amount, { digits: 6, trailingZeros: true }); // 123,456.789000
Significant digits
Significant digits start at the first nonzero digit. Leading zeros do not count, but zeros between significant digits do. Use significantDigits to format small amounts without counting their leading zeros:
dnum.format([126n, 8], { significantDigits: 1 }); // "0.000001"
dnum.format([126n, 8], { significantDigits: 2 }); // "0.0000013"
On its own, significantDigits rounds the whole number to the requested precision. When combined with digits, it preserves whichever precision keeps more detail:
let amount = [1234567n, 3] as const; // 1234.567
dnum.format(amount, { significantDigits: 2 }); // "1,200"
dnum.format(amount, { digits: 2, significantDigits: 2 }); // "1,234.57"
dnum.format([126n, 8], { digits: 2, significantDigits: 2 }); // "0.0000013"
Fractional trailing zeros are trimmed by default. Set trailingZeros: true to pad to the selected precision, including after rounding changes the number’s magnitude:
dnum.format([1n, 6], { significantDigits: 2, trailingZeros: true }); // "0.0000010"
dnum.format([999n, 5], { significantDigits: 2, trailingZeros: true }); // "0.010"
Zero is formatted as "0" by default. With trailingZeros: true, it uses digits fractional places if provided, or significantDigits - 1 otherwise. Rounding follows decimalsRounding: "ROUND_HALF" rounds to the nearest value with ties away from zero, "ROUND_UP" rounds away from zero, and "ROUND_DOWN" rounds toward zero. Locale and sign display options apply as usual. Invalid significantDigits values throw a RangeError; combining it with compact: true throws an error.
from(valueToParse, decimals)
Parse a value and convert it into a Dnum. The passed value can be a string, a number, a bigint, or even a Dnum − which can be useful to change its decimals.
| Name |
Description |
Type |
valueToParse |
Value to convert into a Dnum |
Numberish |
decimals (optional) |
Number of decimals (defaults to true for auto) |
number | true |
| returns |
Converted value |
Dnum |
Example
// Parses a number expressed as a string or number
let amount = dnum.from("17.30624", 18);
// amount equals [17306240000000000000n, 18]
add(value1, value2, decimals)
Adds two values together, regardless of their decimals. decimals correspond to the decimals desired in the result.
| Name |
Description |
Type |
value1 |
First value to add |
Numberish |
value2 |
Second value to add |
Numberish |
decimals (optional) |
Result decimals (defaults to value1 decimals) |
number |
| returns |
Result |
Dnum |
subtract(value1, value2, decimals)
Subtracts the second value from the first one, regardless of their decimals. decimals correspond to the decimals desired in the result.
| Name |
Description |
Type |
value1 |
Value from which value2 is subtracted |
Numberish |
value2 |
Value to subtract from value1 |
Numberish |
decimals (optional) |
Result decimals (defaults to value1 decimals) |
number |
| returns |
Result |
Dnum |
Alias: sub()
multiply(value1, value2, optionsOrDecimals)
Multiply two values together, regardless of their decimals. options.decimals correspond to the decimals desired in the result.
| Name |
Description |
Type |
value1 |
First value to multiply |
Numberish |
value2 |
Second value to multiply |
Numberish |
options.decimals (optional) |
Results decimals (defaults to value1 decimals). Setting options to a number acts as an alias for this option. |
Decimals |
options.rounding (optional) |
How to round round results (defaults to "ROUND_HALF") |
Rounding |
| returns |
Result |
Dnum |
Alias: mul()
Example
let ethPriceUsd = [100000n, 2]; // 1000 USD
let tokenPriceEth = [570000000000000000, 18]; // 0.57 ETH
let tokenPriceUsd = dnum.multiply(tokenPriceEth, ethPriceUsd, 2); // 570 USD
// tokenPriceUsd equals [57000, 2]
divide(value1, value2, optionsOrDecimals)
Divide a value by another one, regardless of their decimals. options.decimals correspond to the decimals desired in the result.
| Name |
Description |
Type |
value1 |
Dividend |
Numberish |
value2 |
Divisor |
Numberish |
options.decimals (optional) |
Results decimals (defaults to value1 decimals). Setting options to a number acts as an alias for this option. |
Decimals |
options.rounding (optional) |
How to round round results (defaults to "ROUND_HALF") |
Rounding |
| returns |
Result |
Dnum |
Alias: div()
Example
let ethPriceUsd = [100000n, 2]; // 1000 USD
let tokenPriceUsd = [57000, 2]; // 570 USD
let tokenPriceEth = dnum.divide(tokenPriceUsd, ethPriceUsd, 18); // 0.57 ETH
// tokenPriceEth equals [570000000000000000, 18]
remainder(value1, value2, decimals)
Equivalent to the % operator: calculate the remainder left over when one operand is divided by a second operand.
| Name |
Description |
Type |
value1 |
Dividend |
Numberish |
value2 |
Divisor |
Numberish |
decimals (optional) |
Result decimals (defaults to value1 decimals) |
number |
| returns |
Result |
Dnum |
Alias: rem()
abs(value, decimals)