JavaScript Number
Subject: JavaScript
In JavaScript, the Number data type represents both integers and floating-point (decimal) numbers. It is a fundamental type used for mathematical calculations and numeric logic.
What is a Number in JavaScript?
JavaScript uses a single number type based on the IEEE 754 double-precision 64-bit binary format. There is no separate type for integers or floats; both are considered as Number.
Example:
Valid Numeric Representations
- Decimal: 42
- Hexadecimal: 0x2A (equals 42)
- Exponential: 2e3 (equals 2000)
- Octal (ES6+): 0o52 (equals 42)
- Binary (ES6+): 0b101010 (equals 42)
Type Checking
Number Precision
JavaScript can handle up to 15 digits of precision.
Common Number Methods
- toFixed(n) - Returns a string with n digits after the decimal point.
- toString() - Converts the number to a string.
- toExponential() - Returns a string in exponential notation.
- toPrecision() - Formats a number to a specified length.
Number Constants
- Number.MAX_VALUE: Largest possible number
- Number.MIN_VALUE: Smallest positive number
- Number.POSITIVE_INFINITY: Infinity
- Number.NEGATIVE_INFINITY: -Infinity
- Number.NaN: "Not a Number"
Example:
Special Numeric Values
- Infinity and -Infinity
- NaN (Not a Number) Occurs when a numeric operation fails.
Number Conversion
- Using
Number()
- Using
parseInt()andparseFloat()
Comparing Numbers
Key Takeaways
- JavaScript uses a single Number type for both integers and floats.
- Special values include NaN, Infinity, and constants like MAX_VALUE.
- Methods like toFixed(), toPrecision(), and toExponential() help format numbers.
- Use parseInt() and parseFloat() to convert strings to numbers.
- Always validate numeric operations to avoid unexpected NaN results.