Skip to main content

Convert amount

Overview

When creating transactions, you need to represent token amounts using hexadecimal strings rather than regular strings. This guide walks you through the conversion process.

Convert amount

The convertAmount function converts a string representation of a number (amount) returns a BigNumber representation, using the specified decimals to determine the number of decimal places::

import { BigNumber, parseFixed } from "@ethersproject/bignumber";

const convertAmount = (amount, decimals) => {
const rawAmount = parseFixed(amount, decimals);
return rawAmount;
};

For example, let's convert 10 RON to HexString:

  1. Start with the token amount as a string:
const amount = "10";
  1. Convert to BigNumber for precision:
import { BigNumber, ethers } from "ethers";

const amount = "10";
const rawAmount = convertAmount(amount, 18); // Precision set to 18 decimals
  1. Transform BigNumber to HexString for transaction usage:
import { BigNumber, ethers } from "ethers";

const amount = "10";
const rawAmount = convertAmount(amount, 18);
const hexAmount = ethers.utils.hexValue(rawAmount);
Was this helpful?
Happy React is loading...