7

I type Math.PI; in Chrome Console and this is returned:

3.141592653589793

Then I type Math.PI - 3.141592653589793; and 0 was returned.

Is there a way to get a more accurate value (such as 3.1415926535897932384) of Math.PI in Javascript?

chris97ong
  • 6,870
  • 7
  • 32
  • 52
  • 1
    Probably not. You can try to calculate pi yourself. – Madara's Ghost Mar 31 '14 at 10:49
  • 1
    Here's a megabyte of pi, help yourself: http://newton.ex.ac.uk/research/qsystems/collabs/pi/pi6.txt But seriously, what are you trying to accomplish that 15 decimal places are not sufficient? Note that rounding errors at this scale are significant. – Piskvor left the building Mar 31 '14 at 10:52
  • 1
    ["Seriously, it does make sense to define "pi" as a defined constant - not because it changes, but because it's tricky to determine the proper source code representation that will give the most accurate value for the number. That's why Java and JavaScript have Math.PI and Math.E final member variables..."](http://c2.com/cgi/wiki?ValueOfPi) – Andy Mar 31 '14 at 10:54

2 Answers2

5

I don't see why you would need PI to such accuracy but you can either :

a) Calculate PI yourself using Leibniz formula

b) Define PI yourself (using this library)

var PI = new bigdecimal.BigDecimal("3.141592653589793238462643383279");


You can find first 100,000 digits of PI here if you really need it.

user3368484
  • 109
  • 4
  • 2
    Option (b) does not work for me: `alert (PI == Math.PI);` returns `true`, while you assert it should *not* be the same. – Jongware Mar 31 '14 at 12:37
  • 1
    One can say `var my_pi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647;` etc. , but end-result will still be dependent on max precision on floating numbers. Typically `alert(my_pi);` will yield `3.141592653589793`. If one want more decimals one need to use an array. But then again it won't be *"of Math.PI"* as OP asks. – user13500 Mar 31 '14 at 12:50
  • 2
    That will still not give you higher precision. `3141592653589793238462643383279/10` will only be accurate to `3.141592653589793` due to floating number limitation. – user13500 Mar 31 '14 at 12:58
  • Sorry, quite new to this. Forgive me if its still wrong :p – user3368484 Mar 31 '14 at 13:12
  • 2
    "BigDecimal for Javascript is a pure-Javascript implementation of immutable, arbitrary-precision, signed decimal numbers." – user3368484 Mar 31 '14 at 13:13
4

The maximum decimal places in javascript is limited to 15.

So you cannot get more than 15 decimal places.

But you can get up to 20 decimal places by doing but its not accurate

Math.PI.toFixed(20); //3.14159265358979311600

That will give you a PI value with 20 decimal places.

Note: 20 is the maximum and 0 is the minimum for toFixed().

So trying Math.PI.toFixed(100) will throw an error.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95