简体   繁体   English

使 JavaScript Math.sqrt() 打印更多数字

[英]Make JavaScript Math.sqrt() print more digits

If I write document.write(Math.sqrt(2)) on my HTML page, I get 1.4142135623730951 .如果我在 HTML 页面上写document.write(Math.sqrt(2)) ,我会得到1.4142135623730951

Is there any way to make the method output more than 16 decimal places?有没有办法让方法输出超过16位小数?

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. Javascript 中的数学运算是使用 64 位浮点值执行的,16 位精度正好在它们可以准确表示的极限附近。

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.不过,我不知道支持平方根的 Javascript 中的任何一个 - 我能够找到的一个 (Big.js) 只支持加法、减法和比较。

You can use toPrecision .您可以使用toPrecision However, ECMA requries only a precision of up to 21 significant digits:但是,ECMA 只需要最多 21 个有效数字的精度:

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 ).但请记住,计算机上实数值的精度有一些限制(请参阅duskwuff 的回答)。

See also:也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM