Moralis.Units.Token() Error: Error: [number-to-bn] while converting number

const ethIn = Moralis.Units.FromWei(amountToTrade, tokenInDecimals);
const cashIn = (ethIn * tokenInPrice.usdPrice * SLIPPAGE).toFixed(18);
const converted = (cashIn / tokenOutPrice.usdPrice).toFixed(18);
const weiOut = Moralis.Units.Token(converted, tokenOutDecimals.toString());

Getting an error when trying to convert from tokens to wei

Error: [number-to-bn] while converting number “0x1ded44.1fdf3b64” to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported. Given value: “0x1ded44.1fdf3b64”

If I change toFixed(18) to toFixed() in “converted”, no errors, but then I’m either rounding up and the transaction will fail because the output is too high, or it will round down and I’ll get a terrible price. The error says decimals are not supported, but the documentation on Unit.Token() shows the token amount as a decimal?

converted.toString() doesn’t fix the issue parseFloat(converted) doesn’t fix the issue, only toFixed(0), which stops the error, but doesn’t fix the issue.

What do I need to do to “converted” for Units.Token() to work properly?

Hey @dataforestLTD

It’s a known issue, we will fix it in the coming versions. For now, I suggest you install bignumber.js (NPM LINK)

The code you can use instead of Moralis.Units.Token:

import BigNumber from 'bignumber.js'

const BIG_TEN = new BigNumber(10)

/**
 * Take a formatted amount, e.g. 15 BNB and convert it to full decimal value, e.g. 15000000000000000
 */
export const getDecimalAmount = (amount: BigNumber, decimals = 18) => {
  return new BigNumber(amount).times(BIG_TEN.pow(decimals))
}