javascript

Working with Numbers


 

Working with numbers in JavaScript is fundamental aspect of programming. JavaScript provided multiple functions and methods to preform task on numbers.

Some basic operations and functions are as follows:

1. Basic Arithmetic Operations

 

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Modulus (%)

 

Example:

// Arithmetic
let a = 10;
let b = 5;
let sum = a + b; // 15
let difference = a - b; // 5
let product = a * b; // 50
let quotient = a / b; // 2
let remainder = a % b; // 0

 

2. Math Object

JavaScript provides a built-in math object that allows you to perform mathematical tasks.

 

Example:

// Math Objects
let radius = 5;
let circumference = 2 * Math.PI * radius;

let angleInRadians = Math.PI / 4;
let sineValue = Math.sin(angleInRadians); // Calculate sine value

let randomNumber = Math.random(); // random number between 0 and 1

 

3. Number Methods 


Numbers in JavaScript are primitive values, but they have some associated methods that can be called on number literals or variables.

 

Example:

// Number methods
let num = 10.86789;
num.toFixed(2); // "10.87"
num.toPrecision(4); // "10.87"
num.toString(); // "10.86789"

 

4.Type Conversion 


JavaScript automatically converts between number types as needed. Manually we can do it by using pasrseInt() and parseFloat().

 

Example:
 

// type conversion
let strNumber = "10";
let parsedInt = parseInt(strNumber); // 10

let floatString = "10.5";
let parsedFloat = parseFloat(floatString); // 10.5