Monday, December 18, 2017

Math Function and Numbers in JavaScript - Day 19

Math Function is used to do mathematical works in JavaScript. Lets know one by one.

  • Math.PI  == Will output the value of PI
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.PI;
</script>

Output:  3.141592653589793

  • Math.round(num) 
Replace num with any decimal numbers. You will get the answer as a whole number which is nearly to the decimal number.

  • Math.pow(x,y) will out put the x to the power of y.
Eg: Math.pow(3,2)
Output: 8

  • Math.sqrt()
The above will give the square root of a given number.
E.g:   Math.sqrt(4)
Output: 2

  • Math.random() will give a random number
  • Math.floor will output the maximum whole number below that decimal number.
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.floor(Math.random()*50);
</script>


The above function will return Random numbers between 50. The output will change time to change when you run the code.

*50 defines the range of Random numbers to be selected.


Math.min() and Math.max()

Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments.

Output the Date & Time using JS

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Date();
</script>


If you want to Output a Particular Date & Time..

<p id="demo"></p>

<script>
var d = new Date("October 13, 2014 11:13:00");
document.getElementById("demo").innerHTML = d;
</script>

Output:    Mon Oct 13 2014 11:13:00 GMT+0530

Numbers

<p id="demo"></p>

<script>
var x = 2456e6;
var y = 2456-5;

document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

Output:
2456000000
0.02456

e means Exponential & e5 means 10 to the powers of 5. e-5 = 10 to the power of -5.

Adding Numbers

<p id="demo"></p>

<script>
var x = 30;
var y = 20;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

Output : 50

Adding Strings & Numbers

<p id="demo"></p>

<script>
var x = "540";
var y = "560";
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

Output: 540560

Here inside the double quotation JS will take as String, therefore it will print as it is.

NaN - Not a Number

NaN is a JavaScript reserved word indicating that a number is not a legal number.

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 100 / "Orange";
</script>

Output: NaN

No comments:

Post a Comment