Number and Maths in JavaScript

Number and Maths in JavaScript

Learn about Numbers and Maths in JS

In JavaScript, dealing with numbers is a fundamental aspect of programming. Let's explore some useful techniques and methods for working with numbers efficiently.

You already know the primary way of defining number data type is /by simply writing "const score = 100" (here javascript automatically detects that type of score is number), but we can explicitly define a variable type to Number, using "new" keyword and "Number" object.

let's learn the concept of Number object.

Number object

While primitive numbers satisfy the need for most scenarios, JavaScript also offers the Number object for explicit number declaration. This can be achieved using the new keyword along with the Number object:

const balance = new Number(100);
console.log(balance); 
//output: [Number: 100]

Now we are using the Number object, we also get different methods that we can use that are provided by the Number objects, for eg:

The Number object provides several handy methods for manipulating numbers:

  • toString(): Converts a number to a string.

  • toFixed(): Formats a number to a fixed-point notation with a specified number of decimal places.

  • toPrecision(): Formats a number to a specified precision.

  • toLocaleString(): Returns a string representing the number formatted according to the locale-specific conventions.

console.log(balance.toString().length); //outputs: 3
//after converting it to string with toString(), we can find the length of the string with the length method

console.log(balance.toFixed(2)); //outputs: 100.00
//toFixed() method rounds the string to a specified number of decimals.

const otherNumber = 23.8966;
console.log(otherNumber.toPrecision(3)); //outputs: 23.9

const otherNumberNew = 123.3966;
console.log(otherNumberNew.toPrecision(4)); //outputs: 123.4

//one more case, what if we
const otherNumberTwo = 1123.8966
console.log(otherNumberTwo.toPrecision(3)); //outputs: 1.12e+3, so be careful with precision method

//another method to make representation easier
const hundreds = 1000000; //outputs: 10,00,000
console.log(hundreds.toLocaleString('en-IN')); //if we dont write em-IN, then it will return value in form of US stndards

Maths in JavaScript

The Math object in JavaScript is a built-in global object providing mathematical functions. It offers a range of methods for performing mathematical operations and manipulating numbers with precision and ease.
The Math object in JavaScript provides a range of mathematical constants and functions:

  • abs(): Returns the absolute value of a number.

  • round(): Rounds a number to the nearest integer.

  • ceil(): Rounds a number up to the nearest integer.

  • floor(): Rounds a number down to the nearest integer.

  • sqrt(): Returns the square root of a number.

  • min(): Returns the minimum value among its arguments.

  • max(): Returns the maximum value among its arguments.

  • random(): Returns a random floating-point number between 0 (inclusive) and 1 (exclusive).

console.log(Math);  //outputs: Object [Math] {}
//Math is an object in itself and in which there are number of properties and functions

console.log(Math.abs(-4)); //outputs: 4
console.log(Math.round(11.3)); //outputs: 11 
console.log(Math.round(4.6)); //outputs: 5

//now if we only want upper values, then we can use ceil funtion
console.log(Math.ceil(7.1)); //outputs: 8

//now if we only want lower values, then we can use floor funtion
console.log(Math.floor(2.9)); //outputs: 2

//we have sqrt also
console.log("square root of 25 is " + Math.sqrt(25)); //outputs: square root of 25 is 5

//if we want to know lowest value and the highest value inside an array, then we can use min and for highest we can use max
console.log("Minimum value is " + Math.min(4,3,6,8)); //outputs: Minimum value is 3
console.log("Maximum value is " + Math.max(4,3,6,8)); //outputs: Maximum value is 8

Generating random numbers in JS

To generate random numbers within a specific range, you can use the Math.random() method in conjunction with appropriate arithmetic:

Math.random() in JavaScript returns a random floating-point number between 0 (inclusive) and 1 (exclusive).

console.log(math.random()); //output: 0.5606390146826902, any random value

console.log((Math.random() * 10) + 1); //output: 5.606390146826902
// "* 10" shifts digit right to the decimal to the left and "+ 1" make sure that there is no edge case 

console.log(Math.floor(Math.random() * 10) + 1); //output: 5
//floor only prints digits left to the decimal making it a whole number
//Math.floor() rounds down to the nearest whole number, effectively removing the decimal part.

This code generates a random number between 1 and 10.

  • Math.random() gives us a random decimal number between 0 (inclusive) and 1 (exclusive).

  • We multiply this by 10 to expand the range to 0 (inclusive) to 10 (exclusive), effectively shifting the decimal point one place to the left.

  • Finally, we add 1 to ensure that we never get a result of 0 and to make sure the range includes 10.

  • Math.floor() rounds down to the nearest whole number, effectively removing the decimal part.

What if we want to print numbers between a certain range

//now suppose we want that we only want values between 10 and 20
const min = 10;
const max = 20;

console.log(Math.floor(Math.random() * (max - min + 1)) + min);
//if you dont get this last explanation, just remember it as a formula
//that multiplying by (max - min + 1)) + min); gives result within desired range
  • Math.random() gives us a random decimal number between 0 (inclusive) and 1 (exclusive).

  • We want our random number to fall within the range of 10 to 20. So, we calculate the range by subtracting the minimum value (10) from the maximum value (20), and then add 1 to include the upper limit.

  • Multiplying this range by Math.random() gives us a random decimal number between 0 (inclusive) and the size of our range (inclusive).

  • Math.floor() rounds down this decimal number to the nearest whole number.

  • Finally, we add the minimum value (10) to ensure that the random number falls within our desired range.