2

If I write document.write(Math.sqrt(2)) on my HTML page, I get 1.4142135623730951.

Is there any way to make the method output more than 16 decimal places?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Bluefire
  • 13,519
  • 24
  • 74
  • 118

2 Answers2

7

No, there is not. Mathematical operations in Javascript are performed using 64-bit floating point values, and 16 digits of precision is right around the limit of what they can represent accurately.

To get more digits of the result, you will need to use an arbitrary-precision math library. I'm not aware offhand of any of these for Javascript that support square roots, though -- the one I was able to find offhand (Big.js) only supports addition, subtraction, and comparisons.

  • I believe they support square roots now. [Quote from the `Features` list](https://github.com/MikeMcl/big.js/#features+): "Includes a `sqrt` method" – Derek 朕會功夫 Apr 09 '14 at 01:26
2

You can use toPrecision. However, ECMA requries only a precision of up to 21 significant digits:

console.log(Math.sqrt(2).toPrecision(21))

But keep in mind that the precision of real values on computer has some limits (see duskwuff's answer).

See also:

Community
  • 1
  • 1
Zeta
  • 103,620
  • 13
  • 194
  • 236
  • 1
    And keep in mind that the additional digits are just a representation of what's in the double. The extra digits past the 16th (or so) will probably *not* be correct for √2. –  Jun 30 '12 at 19:13