What are formatUnits and parseUnits?
In Ethers.js, formatUnits
and parseUnits
are utility functions provided by the library to handle conversions between different units of cryptocurrency, particularly when dealing with values that are represented in Wei (the smallest denomination of Ether) and other units like Ether or custom token units.
Purpose of formatUnits
The formatUnits
function converts a value in Wei (or other denominations) to a human-readable format. It allows you to specify the number of decimal places to format the value accordingly. This is particularly useful when displaying amounts to users, as they typically prefer to see values in Ether or other higher denominations.
Syntax
ethers.utils.formatUnits(value, decimals)
- value
: The value to format (in Wei or other units).
- decimals
: The number of decimal places to include in the output (optional; defaults to 18).
Purpose of parseUnits
The parseUnits
function does the opposite of formatUnits
. It converts a human-readable value (like Ether or token amounts) into Wei (or other lower denominations). This is useful when you need to send a transaction or interact with smart contracts, as they often require values in Wei.
Syntax
ethers.utils.parseUnits(value, decimals)
- value
: The human-readable value to convert (e.g., "1.5" for 1.5 Ether).
- decimals
: The number of decimal places in the original value (optional; defaults to 18).
Sample Code for formatUnits and parseUnits
Below is an example demonstrating how to use formatUnits
and parseUnits
in Ethers.js:
parseUnits
3
Conclusion
The formatUnits
and parseUnits
functions in Ethers.js are essential for converting between human-readable values and their corresponding values in Wei or other denominations. By using these functions, developers can ensure that their applications handle cryptocurrency values accurately and present them in a user-friendly manner.