JavaScript Numbers
The `Number` object in JavaScript is a wrapper object that allows you to work with numerical values. This page will cover basic numeric operations, properties, and methods available for the `Number` object.
1. Basic Numeric Operations
JavaScript supports basic arithmetic operations like addition, subtraction, multiplication, and division using standard operators.
const a = 10;
const b = 5;
const sum = a + b; // 15
const difference = a - b; // 5
const product = a * b; // 50
const quotient = a / b; // 2
const remainder = a % b; // 0
2. Number Properties
JavaScript provides several properties for working with numerical values, including constants for mathematical calculations.
console.log(Number.MAX_VALUE); // Maximum value a number can be
console.log(Number.MIN_VALUE); // Minimum value a number can be
console.log(Number.NaN); // Represents "Not-a-Number"
console.log(Number.POSITIVE_INFINITY); // Positive infinity
console.log(Number.NEGATIVE_INFINITY); // Negative infinity
3. Number Methods
The `Number` object has several useful methods for number manipulation and conversion.
const num = 123.456;
console.log(num.toFixed(2)); // '123.46' - Rounds the number to 2 decimal places
console.log(num.toPrecision(5)); // '123.46' - Formats the number to 5 significant digits
console.log(num.toString()); // '123.456' - Converts the number to a string
console.log(Number.parseInt('101', 2)); // 5 - Parses a string argument and returns an integer (base 2)
console.log(Number.isNaN(NaN)); // true - Checks if the value is NaN
console.log(Number.isFinite(123)); // true - Checks if the value is a finite number
4. Number Conversion
JavaScript can convert between strings and numbers using methods and constructors.
const str = '42';
const num = Number(str); // Converts string to number
console.log(num + 8); // 50
const invalid = 'abc';
const converted = Number(invalid); // NaN - Conversion failed
console.log(converted);