In JavaScript, numbers are a primitive data type used to represent numeric values, including integers and floating-point numbers (decimals). Here's how you can work with numbers in JavaScript:
JavaScript represents all numbers as floating-point values, even integers. You can use both integers and floating-point numbers interchangeably.
let integer = 10;
let float = 3.14;
JavaScript supports various arithmetic operations on numbers, such as addition, subtraction, multiplication, division, and modulus.
let sum = 10 + 5; // Addition
let difference = 10 - 5; // Subtraction
let product = 10 * 5; // Multiplication
let quotient = 10 / 5; // Division
let remainder = 10 % 3; // Modulus (remainder of division)
JavaScript provides a built-in Math object with properties and methods for mathematical operations.
console.log(Math.PI); // Output: 3.141592653589793
console.log(Math.sqrt(25)); // Output: 5 (Square root)
console.log(Math.pow(2, 3)); // Output: 8 (Exponentiation)
console.log(Math.random()); // Output: Random number between 0 and 1
NaN is a special value representing Not a Number. It is returned when a mathematical operation fails.
console.log(10 / "a"); // Output: NaN
Infinity represents positive infinity, while -Infinity represents negative infinity.
console.log(1 / 0); // Output: Infinity
console.log(-1 / 0); // Output: -Infinity
JavaScript provides methods for working with numbers, such as parseInt() and parseFloat() for parsing strings into numbers.
let numStr = "10";
let num = parseInt(numStr); // Convert string to integer
console.log(num); // Output: 10
JavaScript provides methods like toFixed() for formatting numbers to a fixed number of decimal places.
let num = 3.14159;
console.log(num.toFixed(2)); // Output: "3.14"
Example Usage:
Here's an example demonstrating various operations with numbers in JavaScript:
let sum = 10 + 5;
let difference = 10 - 5;
let product = 10 * 5;
let quotient = 10 / 5;
let remainder = 10 % 3;
console.log(sum, difference, product, quotient, remainder);
Numbers are a fundamental data type in JavaScript, used to represent numeric values in various contexts, including mathematical calculations, data processing, and more. By understanding how to work with numbers and perform arithmetic operations, you can effectively manipulate numeric data in your JavaScript programs. JavaScript provides built-in objects and methods for advanced mathematical operations and number formatting, allowing you to perform complex computations with ease.