Search code examples
javascriptweb3js

Why web3 utils BN not work correct with math?


I am trying do this:

import { BN } from 'web3-utils'

const AmountBN = new BN('1000000000000000000')
const res = AmountBN.mul(99).div(100)
console.log(res)  

And get this

Uncaught (in promise) RangeError: Invalid array length at BN.mul (bn.js:1862)


Solution

  • it is somewhat inflexible, but mul() and div() also expect BN as parameters, not numbers. And the result is a BN again, use toString()

    So you need to write something like this:

    const res = AmountBN.mul(new BN('99')).div(new BN('100'))
    console.log(res.toString())