In javaScript, we use different math methods in math object to do mathematical calculation.
Some important method is as follows
Using this method, the absolute (positive) value of the number is displayed in the webpage.
Example 1
<!DOCTYPE html> <html> <head> <title></title> </head> <body> Absolute value of -1 is: <span id="ab"></span> <script> document.getElementById('ab') .innerHTML=Math.abs(-1); </script> </body> </html> |
Output
Absolute value of -1 is: 1 |
Using this method, the decimal number is rounded off, thereby displaying the integer number.
example 2
<!DOCTYPE html> <html> <head> <title></title> </head> <body> Round of 3.3 is: <span id="num1"></span> <br>
Round of 4.6 is: <span id="num2"></span> <script> document.getElementById('num1') .innerHTML=Math.round(3.3); document.getElementById('num2') .innerHTML=Math.round(4.6); </script> </body> </html> |
Output
Round of 3.3 is: 3 |
Using this method, adding 1 number to a decimal number displays the value in the web page, the value after decimal (decimal) is not displayed because using it causes the value round off.
Example
<!DOCTYPE html> <html> <head> <title></title> </head> <body> Ceil of 3.7 is: <span id="num"></span> <script> document.getElementById('num') .innerHTML=Math.ceil(3.7); </script> </body> </html> |
Output
Ceil of 3.7 is: 4 |
Using this method subtract 1 number in decimal number and display value in web page after decimal (decimal) value is not displayed because using it causes value round off.
Example
<!DOCTYPE html> <html> <head> <title></title> </head> <body> Floor of 3.7 is: <span id="num"></span> <script> document.getElementById('num') .innerHTML=Math.floor(3.7); </script> </body> </html> |
Output
Floor of 3.7 is: 3 |
This method calculates the power of the number and displays the number.
Example
<!DOCTYPE html> <html> <head> <title></title> </head> <body> 2 to the power of 4 is: <span id="num"></span> <script> document.getElementById('num') .innerHTML=Math.pow(2,4); </script> </body> </html> |
Output
2 to the power of 4 is: 16 |
To extract the square root of a number, we use the Math.sqrt (n) method.
Example
<!DOCTYPE html> <html> <head> <title></title> </head> <body> Square Root of 144 is: <span id="num1"></span> <script> document.getElementById('num1') .innerHTML=Math.sqrt(144); </script> </body> </html> |
Output
Square Root of 144 is: 12 |