19. JavaScript Math Object

JavaScript Math Object

Math object
Mathematical constants
Mathematical methods
Examples

Math object

Math object includes several mathematical constants and methods.
var pi_value=Math.PI
var sqrt_value=Math.sqrt(16)

Mathematical Constants

8 mathematical constants that can be accessed from the math object.
E Math.E
PI Math.PI
square root of 2 Math.SQRT2
square root of 1/2 Math.SQRT1_2
natural log of 2 Math.LN2
natural log of 10 Math.LN10
base -2 log of E Math.LOG2E
base 10 log of E Math.LOG10E

Mathematical Methods

round() method of the math object to round a number to the nearest integer.
document.write(Math.round(4,7));
ouput: 5

random() method of the math object to return a random number between 0 and 1
document.write(Math.random());
output: 0.07730209357983464

floor() and random() methods of the Math object to return a random number between 0 and 10:
document.write(Math.floor(Math.random()*11));
output:1

Examples:
how to use round()
<html>
<body>
<script type="text/javascript">
document.write(Math.round(0.60)+"<br/>");
document.write(Math.round(0.50)+"<br/>");
document.write(Math.round(0.49)+"<br/>");
document.write(Math.round(-4.40)+"<br/>");
document.write(Math.round(-4.60));
</script>
</body>
</html>
how to use random() to return a trandom number between 0 and 1
<html>
<body>
<script type="text/javascript">
// return a random number between 0 and 1
document.write(Math.random()+"<br/>");
//return a random number between 0and 10
document.write(Math.floor(Math.random()*11);
</script>
</body>
</html>
how to use max() to return the largest of the specified values
<html>
<body>
<script type="text/javascript">
document.write(Math.max(5,10)+"<br/>");
document.write(Math.max(0,150,30,20,38)+"<br/>");
document.write(Math.max(-5,10)+"<br/>");
document.write(Math.max(1.5,2.5));
</script>
</body>
</html>
how to use min() to return the smallest of the specified values.
<html>
<body>
<script type="text/javascript">
document.write(Math.min(5,10)+"<br/>");
document.write(Math.min(0,150,30,20,38)+"<br/>");
document.write(Math.min(-5,10)+"<br/>");
document.write(Math.min(1.5,2.5));
</script>
</body>
</html>

No comments:

My Favorite Books

  • C and Data Structures by Ashok N. kamthane
  • Web Technologies by A. A. Puntambekar
  • Learn HTML and CSS with W3Schools
  • Learn JavaScript and Ajax with W3Schools
  • HTML5 Black Book: Covers Css3, Javascript,XML, XHTML, Ajax, PHP And Jquery
  • HTML5 Application Development Fundamentals: MTA Exam 98-375
  • .NET 4.0 Programming 6-In-1, Black Book
  • SQL Server 2008 R2 Black Book
  • Asp.net 4.0 Projects Covers: net 3.5 And .net 4.0 Codes, Black Book
  • UNIX Shell Programming 1 Edition by Yashavant Kanetkar
  • UNIX and Shell Programming 1 Edition by Richard F. Gilberg, Behrouz A. Forouzan
  • Computer Networks by Andrew S. Tanenbaum
  • Multiple Choice questions in computer science by Timothy J Williams