Math Object
The Math object works by performing normal arithmetic tasks.
The Math object provides a variety of arithmetic value types and functions. You do not need to define it before using this object.
Arithmetic value
JavaScript provides 8 arithmetic values that can be accessed by the Math object:
- Constant
- Pi
- Square root of 2
- Square root of 1/2
- Natural logarithm of 2
- Natural logarithm of 10
- Logarithm of E with base 2
- Logarithm of E with base 10
This is the method of using these values in Javascript: (corresponds to the above arithmetic value one by one)
- Math.e
- Math.PI
- Math.sqrt2
- Math.sqrt1_2
- Math.ln2
- Math.ln10
- math.log2e
- math.log10e
Arithmetic method
In addition to the arithmetic values that can be accessed by the Math object, there are several functions (methods) that can be used.
Example of a function (method):
The following example rounds a number by using the round method of the Math object.
document.write ( Math.round(4.7)
)
The above code output is:
5
The following example uses the random () method of the Math object to return an arbitrary number between 0 and 1:
document.write ( Math.random()
)
The above code output is:
0.9370844220218102
The following example uses the floor () method and random () of the Math object to return a random number between 0 and 10:
document.write (Math.floor(Math.random()*11)
The above code output is:
3
Compare size, return a large value
<body>
<script type= "Text/javascript" >
document.write (Math.max (5,7) + "<br/>")
document.write (Math.max ( -3,5) + "<br/>")
document.write (Math.max ( -3,-5) + "<br/>")
document.write (Math.max (7.25,7.30))
</script>
</body>
Compare size, return a small value
<body>
<script type= "Text/javascript" >
document.write (Math.min (5,7) + "<br/>")
document.write (Math.min ( -3,5) + "<br/>")
document.write (Math.min ( -3,-5) + "<br/>")
document.write (Math.min (7.25,7.30))
</script>
</body>
JavaScript arithmetic objects