skip to Main Content

I have a string which I need to convert to number.

The thing is, I have 20 decimals and JS lose precision after 15 or 17 decimals, when trying to use parseFloat.

Example:

const number = "0.0000012726726461401083"
const parseNumber = parseFloat(number) // 0.0000012726726461401084

Y try to see if libraries like big.js or decimal.js could help me, but I didn’t find any solution.

2

Answers


  1. What didn’t suit you about decimal.js ? It looks exactly like what you would need for that, so have a go at it and try to manually set the precision : https://mikemcl.github.io/decimal.js/#precision

    Login or Signup to reply.
  2. You can use decimal.js like this:

    const number = "0.0000012726726461401083";
    const decimalNumber = new Decimal(number);
    console.log(decimalNumber.toString()); // Outputs: 0.0000012726726461401083
    <script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/9.0.0/decimal.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search