Math…I know…some of you are letting our a collective groan. Let’s face it, not all of us like math, but it is necessary and can be very helpful in developing applications. Fortunately, JavaScript has some built in Math methods to assist us.

- PI – returns 3.14….
- round() – round floating point to nearest integer
- floor() – round floating point down
- ceil() – round floating point up
- random() – generate random number between 0 and 1

There is also, min(), max() and abs(), which returns an absolute number.

So if you need to perform any of these mathematical calculations, let the JavaScript engine do it for you.

1 2 3 4 5 |
var num = 1.234; console.log(Math.round(num));// returns 1 console.log(Math.floor(num));// returns 1 console.log(Math.ceil(num));// returns 2 console.log(Math.random());// returns value between 0 & 1 |

Note: If you want a random number between numbers other than 0 & 1, you can do that easily enough…

1 |
Math.floor((Math.random() * 0) + 1);// Returns random number between 0 and 50 |

Happy Coding!

Clay Hess