javascriptfloating-pointprecisionweb3jsfloating

Float loses precision in javascript


I have an amount of tokens I want to burn in a web3 project. this amount is 0.29806008728157019 I want to pass this amount to web3.utils.toBN(Math.trunc(amount * 1000000000000000000)); as it is without changing it . the problem that I can't pass it as String and when I parse it using ParsFloat it becomes 0.2980600872815702 and this is a problem because I want exactly the same float.

I tried to use toFixed(17) and toPrecision(17) but they change the float to string and the same problem occurs.

So how I can pass it as a float without changing it?


Solution

  • The BigNumber library requires integers. Therefore, you need to use a BigDecimal library to perform the multiplication.

    Then you would do:

    let bn = web3.utils.toBN((new bigDecimal("0.29806008728157019"))
      .multiply(new bigDecimal("1000000000000000000"))
      .floor().getValue());