So for this post I’m gonna show how to do simple math in NodeJS. In further tutorials I will start to explain the rest but for now let’s get to the basics. So let’s start with addition, subtraction, multiplication, and division. This is the most easiest thing to do, all you do is:

console.log(2+2);
console.log(2-2);
console.log(2*2);
console.log(2/2);

results:
4
0
4
1

Now, you might want to have the calculations done in a specific order or want to do something like (3+8)/(3-8). All you have to do is:

console.log((3+8)/(3-8));

Result: -2.2

To do simple equations just do it with each calculation in its own ().

so now that that is done let’s get into the Math Object. The Math Object let’s you do more mathematical tasks. Let’s start with rounding, for this there are 4 things to know: round, ceil, floor, and trunc. Round is simple as it rounds normally, ceil rounds to the highest number for example 7.2 would become 8, floor rounds to the lowest number so 8.9 would become 8, trunc returns the absolute number basically taking out the decimal making 7.6 turn into 7. An extra function is sign which tells if the number is positive, negative, or 0.

now for the code part:

console.log(Math.round(5.6));
console.log(Math.ceil(6.2));
console.log(Math.floor(7.8));
console.log(Math.trunc(5.5));
console.log(Math.sign(-32));

var sign = -32

if(Math.sign(sign) == -1){
console.log(“This is a negative number”)
} else if(Math.sign(sign) == 1){
console.log(“This is a positive number”)
} else if(Math.sign(sign) == 0){
console.log(“This is a 0”)
}

Now lets get to the final part. This section will include PI, Square Root, power, absolute, min, max, and random. The PI task returns the numbers that represent pi. The square root or sqrt returns the square root of a given number. The power will multiply a number to the x power for example 5^2 or pow(5, 2) would return 25. Absolute will put a number to its absolute positive, for example -2 will become 2. The min will return the lowest number in an array while the max will return the highest. The random task will return a random number, however if you are trying to pick a number between 1 and 10 then you will need to do Math.floor(Math.random() * (10-0)) + 0. Now let’s get the the code part:

console.log(Math.PI);
console.log(Math.sqrt(7));
console.log(Math.pow(9, 23));
console.log(Math.min(1, 3, 8, 9, 6, 11));
console.log(Math.max(223, 43, 22, 94, 82, 48));
comsole.log(Math.abs(-23.2));
console.log(Math.random());
console.log(Math.floor(Math.random() * (10-0)) + 0);

If you have any questions contact me at [email protected]