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:
// 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
JavaScript provides a built-in math object that allows you to perform mathematical tasks.
// 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
Numbers in JavaScript are primitive values, but they have some associated methods that can be called on number literals or variables.
// Number methods
let num = 10.86789;
num.toFixed(2); // "10.87"
num.toPrecision(4); // "10.87"
num.toString(); // "10.86789"
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