A transportable object for token amounts with formatting.
Add it to your project:
yarn add token-amount
Use it:
import TokenAmount from 'token-amount'
const amount = new TokenAmount('9388295879707883945', 18, { symbol: 'ANT' })
console.log(amount.format()) // '9.39 ANT'
Instantiates a new TokenAmount
with the given value
and decimals
. The options are optional, and can take a symbol
(e.g. "ANT"
).
value
: the amount value, as aBigInt
,String
,Number
orBigInt
-like (e.g. BN.js).decimals
: the amount of decimals, as aBigInt
,String
,Number
orBigInt
-like (e.g. BN.js).symbol
: the token symbol, as aString
.
Formats the token amount.
options.symbol
: the token symbol, as aString
. Overrides the value set in the constructor.options.commify
: whether the formatted amount should include comma separatorsoptions.digits
: the number of digits to display. Defaults to2
.options.displaySign
: whether the sign (-
or+
) should be displayed for the amount.
Alias to TokenAmount#format().
Static equivalent of TokenAmount#format()
, with the TokenAmount
instance passed as a first parameter.
Converts from a rate, returning a new TokenAmount
instance with the desired decimals and set options. The conversion rate is expressed as the amount of the output token obtained per unit of the input token. An example would be:
- Input token: ANT
- Output token: ETH
- Amount of ANT: 10
- Conversion rate: 0.5 ETH per ANT. (1 ANT = 0.5 ETH)
- Converted Amount = 10 * 0.50 = 5 ETH.
rate
: the rate to convert from, as aString
or aNumber
.targetDecimals
: the target amount of decimals for the output, as aBigInt
,String
,Number
orBigInt
-like (e.g. BN.js).options.symbol
: the token symbol, as aString
.
Static equivalent of TokenAmount#convert()
, with the TokenAmount
instance passed as a first parameter.
Exports the object into a string that can get stored or transported.
Instantiates a new instance by importing a string generated by TokenAmount#export()
.