最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Make JavaScript Math.sqrt() print more digits - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Sep 15, 2020 at 15:15 Penny Liu 17.6k5 gold badges86 silver badges108 bronze badges asked Jun 30, 2012 at 18:59 BluefireBluefire 14.1k24 gold badges79 silver badges121 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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 parisons.

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 puter has some limits (see duskwuff's answer).

See also:

  • toFixed
  • toExponential
发布评论

评论列表(0)

  1. 暂无评论