Math Constants in JavaScript:
Math.E, Math.PI, and more

JavaScript FAQ | JavaScript Numbers FAQ  

Question: How do I handle mathematical constants in JavaScript?

Answer: In JavaScript, some mathematical constants are predefined – they are properties of the Math object. You can write these constants as follows:

Math.PI      // pi = 3.14159265...
Math.E       // e = 2.71828182...
Math.LOG2E   // log of e base 2
Math.LOG10E  // log of e base 10
Math.LN2     // log of 2 base e
Math.LN10    // log of 10 base e
Math.SQRT2   // square root of 2
Math.SQRT1_2 // square root of 1/2
Thus, there is no need to remember the exact value of e or π. Just use Math.E or Math.PI! Here is a simple code example that computes the radius of the Earth in kilometers and in miles using Math.PI:
var rkm = 20000/Math.PI;
var rmi = 20000/(1.609344*Math.PI);

document.write(
  "The Earth's radius is "
 +rkm.toFixed()+" km, or "
 +rmi.toFixed()+" miles. "
);
This code produces the following output:

See also:

  • JavaScript number literals aka constants
  • Math functions in JavaScript
  • Can I display mathematical symbols as part of JavaScript output?
  • Can I display Greek letters on my page as part of JavaScript output?
  • Accuracy of JavaScript computations
  • Copyright © 1999-2012, JavaScripter.net.