Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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:

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top