1

I am trying to remake google calculator but only with square and power of two, you can type a number and just click to get square root of two from the number, you can also click to make number squared.

Everything works fine but after you click root and then power you get slightly different value.

I tried a few javascript methods like toFixed() but for different values you have to sometimes round it and sometimes floor it for example after getting the root and exponentiating from:

  • 2 it's 2.0000000000000004 so the result would have to be smaller
  • 3 it's 2.9999999999999996 so the result would have to be bigger
DGX37
  • 304
  • 3
  • 12

1 Answers1

1

For floating point precision I would suggest to use a library, like Decimal.js. It obscures the solution to the rounding errors.

For example, instead of doing Math.pow(Math.sqrt(2), 2), you would do:

Decimal.sqrt(2).toPower(2).toNumber(); // 2
m.spyratos
  • 3,823
  • 2
  • 31
  • 40