JavaScript numbers are a versatile and crucial part of the language. They represent both integers and floating-point numbers and come with a variety of methods and properties to perform operations.
This tutorial will introduce JavaScript numbers, how to use them, and demonstrate several built-in methods for working with numeric data.
Table of Contents
1. Basic Usage of Numbers in JavaScript
In JavaScript, numbers are represented using the 64-bit floating-point format. This allows for the representation of both integers and floating-point (decimal) numbers.
Example 1: Defining Numbers
// Integer const integerNumber = 42; // Floating-point number const floatingPointNumber = 3.14; console.log(integerNumber); // Output: 42 console.log(floatingPointNumber); // Output: 3.14
Explanation: JavaScript numbers can be integers or decimals. Both are represented using the Number type.
2. Number Properties and Constants
JavaScript provides several built-in properties and constants for numbers:
Number.MAX_VALUE: The largest positive number that can be represented.
Number.MIN_VALUE: The smallest positive number that can be represented.
Number.POSITIVE_INFINITY: Represents infinity.
Number.NEGATIVE_INFINITY: Represents negative infinity.
Number.NaN: Represents “Not-a-Number.”
Example 2: Using Number Properties
console.log(Number.MAX_VALUE); // Output: 1.7976931348623157e+308 console.log(Number.MIN_VALUE); // Output: 5e-324 console.log(Number.POSITIVE_INFINITY); // Output: Infinity console.log(Number.NEGATIVE_INFINITY); // Output: -Infinity console.log(Number.NaN); // Output: NaN
3. Number Methods
3.1 toString() Method
Converts a number to a string. You can optionally specify a base (radix) for the conversion (e.g., binary, octal, hexadecimal).
Example 3: Using toString()
const number = 255; console.log(number.toString()); // Output: '255' console.log(number.toString(2)); // Output: '11111111' (binary) console.log(number.toString(16)); // Output: 'ff' (hexadecimal)
3.2 toFixed() Method
Formats a number to a specified number of decimal places and returns it as a string.
Example 4: Using toFixed()
const pi = 3.14159; console.log(pi.toFixed(2)); // Output: '3.14' console.log(pi.toFixed(4)); // Output: '3.1416'
Explanation: The toFixed() method rounds the number to the specified decimal places.
3.3 toPrecision() Method
Formats a number to a specified length, including both the integer and decimal parts.
Example 5: Using toPrecision()
const num = 123.456; console.log(num.toPrecision(4)); // Output: '123.5' console.log(num.toPrecision(6)); // Output: '123.456' console.log(num.toPrecision(2)); // Output: '1.2e+2'
Explanation: toPrecision() provides a way to format a number to a specific number of significant digits.
3.4 Number.isInteger() Method
Checks if a value is an integer.
Example 6: Using Number.isInteger()
console.log(Number.isInteger(42)); // Output: true console.log(Number.isInteger(3.14)); // Output: false console.log(Number.isInteger('42')); // Output: false Explanation: Number.isInteger() returns true if the number is an integer; otherwise, it returns false.
3.5 Number.isNaN() Method
Determines if a value is NaN (Not-a-Number).
Example 7: Using Number.isNaN()
console.log(Number.isNaN(NaN)); // Output: true console.log(Number.isNaN(42)); // Output: false console.log(Number.isNaN('Hello')); // Output: false console.log(Number.isNaN(Number('Hello'))); // Output: true
Explanation: Number.isNaN() is used to check if a value is NaN. Note that Number.isNaN() is different from the global isNaN() function because it does not attempt to convert the value to a number before checking.
3.6 parseInt() and parseFloat() Functions
parseInt(): Parses a string and returns an integer.
parseFloat(): Parses a string and returns a floating-point number.
Example 8: Using parseInt() and parseFloat()
console.log(parseInt('42')); // Output: 42 console.log(parseInt('3.14')); // Output: 3 console.log(parseFloat('3.14')); // Output: 3.14 console.log(parseInt('1010', 2)); // Output: 10 (binary to decimal)
Explanation: parseInt() can also accept a second argument to specify the base (radix) of the number in the string (e.g., binary, octal, hexadecimal).
4. Math Object for Numerical Operations
JavaScript provides the Math object for complex mathematical operations.
Example 9: Common Math Methods
console.log(Math.round(4.7)); // Output: 5 (Rounds to the nearest integer) console.log(Math.ceil(4.2)); // Output: 5 (Rounds up) console.log(Math.floor(4.8)); // Output: 4 (Rounds down) console.log(Math.max(10, 20, 30)); // Output: 30 (Finds the maximum value) console.log(Math.min(10, 20, 30)); // Output: 10 (Finds the minimum value) console.log(Math.sqrt(16)); // Output: 4 (Square root) console.log(Math.pow(2, 3)); // Output: 8 (2 raised to the power of 3) console.log(Math.random()); // Output: Random number between 0 (inclusive) and 1 (exclusive)
5. Working with Infinity and NaN
JavaScript has Infinity and NaN to handle extreme or invalid operations.
Example 10: Using Infinity and NaN
console.log(1 / 0); // Output: Infinity console.log(-1 / 0); // Output: -Infinity console.log(0 / 0); // Output: NaN console.log(Number.isFinite(100)); // Output: true console.log(Number.isFinite(Infinity)); // Output: false
Explanation: Dividing a number by zero results in Infinity or -Infinity. Dividing zero by zero results in NaN. Number.isFinite() checks if a number is finite.
6. Number Conversion
You can convert other types to numbers using Number(), parseInt(), or parseFloat().
Example 11: Number Conversion
console.log(Number('123')); // Output: 123 console.log(Number('123.45')); // Output: 123.45 console.log(Number('abc')); // Output: NaN console.log(parseInt('1010', 2)); // Output: 10 (Binary to decimal) console.log(parseFloat('3.14')); // Output: 3.14
Explanation: Number() converts a string to a number. If the string is not a valid number, it returns NaN.
7. Handling Floating-Point Precision Issues
JavaScript uses floating-point arithmetic, which can sometimes lead to precision issues.
Example 12: Floating-Point Precision Issue
console.log(0.1 + 0.2); // Output: 0.30000000000000004
Explanation: Due to how floating-point arithmetic works, adding 0.1 and 0.2 results in a small precision error. A common workaround is to use the toFixed() method to round the number.
Example 13: Fixing Floating-Point Precision
const sum = 0.1 + 0.2; console.log(sum.toFixed(2)); // Output: '0.30'
Conclusion
JavaScript numbers are flexible and versatile, offering numerous methods and properties for handling various numerical operations.
Understanding how to use these methods, handle special values like NaN and Infinity, and manage precision issues is crucial when working with numeric data.
This tutorial covers the essential aspects of JavaScript numbers, including creating, converting, and performing operations on them.
Experiment with these examples to gain confidence in using numbers in your JavaScript code!