Display Logic and Input

When creating an Application, it is useful to convert between user-friendly strings (usually displaying ether) and the machine-readable values that contracts and maths depend on (usually in wei).

For example, a Wallet may specify the balance in ether, and gas prices in gwei for the User Interface, but when sending a transaction, both must be specified in wei.

The parseUnits will parse a string representing ether, such as 1.1 into a BigNumber in wei, and is useful when a user types in a value, such as sending 1.1 ether.

The formatUnits will format a BigNumberish into a string, which is useful when displaying a balance.

Units

Decimal Count

A Unit can be specified as a number, which indicates the number of decimal places that should be used.

Examples:

Named Units

There are also several common Named Units, in which case their name (as a string) may be used.

NameDecimals 
wei0 
kwei3 
mwei6 
gwei9 
szabo12 
finney15 
ether18 

Functions

Formatting

ethers.utils.commify( value ) string

Returns a string with value grouped by 3 digits, separated by ,.

commify("-1000.3000"); // '-1,000.3'

Conversion

ethers.utils.formatUnits( value [ , unit = "ether" ] ) string

Returns a string representation of value formatted with unit digits (if it is a number) or to the unit specified (if a string).

const oneGwei = BigNumber.from("1000000000"); const oneEther = BigNumber.from("1000000000000000000"); formatUnits(oneGwei, 0); // '1000000000' formatUnits(oneGwei, "gwei"); // '1.0' formatUnits(oneGwei, 9); // '1.0' formatUnits(oneEther); // '1.0' formatUnits(oneEther, 18); // '1.0'
ethers.utils.formatEther( value ) string

The equivalent to calling formatUnits(value, "ether").

const value = BigNumber.from("1000000000000000000"); formatEther(value); // '1.0'
ethers.utils.parseUnits( value [ , unit = "ether" ] ) BigNumber

Returns a BigNumber representation of value, parsed with unit digits (if it is a number) or from the unit specified (if a string).

parseUnits("1.0"); // { BigNumber: "1000000000000000000" } parseUnits("1.0", "ether"); // { BigNumber: "1000000000000000000" } parseUnits("1.0", 18); // { BigNumber: "1000000000000000000" } parseUnits("121.0", "gwei"); // { BigNumber: "121000000000" } parseUnits("121.0", 9); // { BigNumber: "121000000000" }
ethers.utils.parseEther( value ) BigNumber

The equivalent to calling parseUnits(value, "ether").

parseEther("1.0"); // { BigNumber: "1000000000000000000" } parseEther("-0.5"); // { BigNumber: "-500000000000000000" }