JavaScript Numbers
Master JavaScript numbers: learn number types, operations, built-in methods, and the Math object. Work with numeric data efficiently and handle special values.
What You'll Learn
What Are Numbers?
In JavaScript, a number is a numeric data type that represents both integers and decimal values. JavaScript uses a single number type: 64-bit floating-point numbers following the IEEE 754 standard. This means all numbers are stored the same way, whether they're integers or decimals.
Creating Numbers
You can create numbers by writing numeric literals or using the Number constructor:
Numeric Literals
// Integer
let age = 25;
let count = -5;
// Decimal (Float)
let price = 19.99;
let temperature = -3.5;
// Scientific notation
let large = 1.5e10; // 1.5 × 10^10 = 15000000000
let small = 2e-3; // 2 × 10^-3 = 0.002
// Hex, Octal, Binary (different bases)
let hexNumber = 0xFF; // 255
let octalNumber = 0o10; // 8
let binaryNumber = 0b1010; // 10
Using Number Constructor
let x = Number("42"); // 42
let y = Number("3.14"); // 3.14
let z = Number(true); // 1
let w = Number(false); // 0
let invalid = Number("abc"); // NaN
Arithmetic Operations
JavaScript supports standard arithmetic operations with numbers:
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 10 + 5 | 15 |
- |
Subtraction | 10 - 5 | 5 |
* |
Multiplication | 10 * 5 | 50 |
/ |
Division | 10 / 5 | 2 |
% |
Modulo (remainder) | 10 % 3 | 1 |
** |
Exponentiation | 2 ** 3 | 8 |
++ |
Increment | x++ | Adds 1 to x |
-- |
Decrement | x-- | Subtracts 1 from x |
Arithmetic Examples
let a = 10;
let b = 3;
// Basic operations
// a + b = 13
// a - b = 7
// a * b = 30
// a / b = 3.333...
// a % b = 1 (remainder)
// a ** 2 = 100 (square)
// Operator precedence (follows PEMDAS)
let result = 10 + 5 * 2; // 20 (multiply first)
let result2 = (10 + 5) * 2; // 30 (parentheses first)
// Compound assignment
let x = 10;
x += 5; // x = 15 (same as x = x + 5)
x -= 3; // x = 12 (same as x = x - 3)
x *= 2; // x = 24 (same as x = x * 2)
x /= 4; // x = 6 (same as x = x / 4)
Number Methods
JavaScript provides built-in methods to work with and format numbers:
toFixed() - Decimal Places
// toFixed(digits) - returns string with fixed decimal places
let pi = 3.14159;
// pi.toFixed(2) returns "3.14"
// pi.toFixed(0) returns "3"
// pi.toFixed(4) returns "3.1416"
let price = 19.5;
// price.toFixed(2) returns "19.50"
// Note: toFixed() returns a string, not a number
let fixed = (10.5).toFixed(1); // "10.5" (string)
toPrecision() - Significant Digits
// toPrecision(digits) - significant figures
let num = 123.456;
// num.toPrecision(3) returns "123"
// num.toPrecision(5) returns "123.46"
// num.toPrecision(7) returns "123.456"
// Works with large numbers too
let big = 123456;
// big.toPrecision(3) returns "1.23e+5" (scientific notation)
toString() - Convert to String
// toString() - convert number to string
let num = 255;
// num.toString() returns "255"
// num.toString(2) returns "11111111" (binary)
// num.toString(16) returns "ff" (hexadecimal)
let decimal = 42;
// decimal.toString() returns "42"
// (3.14).toString() returns "3.14"
The Math Object
JavaScript provides a Math object with mathematical methods and constants:
Math Constants
// Math constants
// Math.PI = 3.141592653589793
// Math.E = 2.718281828459045
// Math.LN2 = 0.6931471805599453
// Math.LN10 = 2.302585092994046
// Math.SQRT2 = 1.4142135623730951
// Examples
let circumference = 2 * Math.PI * radius;
let eToThePower = Math.E ** 2;
Math Methods - Rounding
// Math.round() - rounds to nearest integer
// Math.round(4.7) returns 5
// Math.round(4.4) returns 4
// Math.round(-4.7) returns -5
// Math.ceil() - rounds up
// Math.ceil(4.2) returns 5
// Math.ceil(-4.2) returns -4
// Math.floor() - rounds down
// Math.floor(4.9) returns 4
// Math.floor(-4.9) returns -5
// Math.trunc() - removes decimal part
// Math.trunc(4.9) returns 4
// Math.trunc(-4.9) returns -4
Math Methods - Power, Square Root, Absolute
// Math.pow(base, exponent)
// Math.pow(2, 3) returns 8
// Math.pow(10, 2) returns 100
// Math.sqrt(number) - square root
// Math.sqrt(16) returns 4
// Math.sqrt(2) returns 1.4142135623730951
// Math.abs(number) - absolute value
// Math.abs(-5) returns 5
// Math.abs(-3.14) returns 3.14
// Math.min() and Math.max()
// Math.min(3, 5, 1, 9) returns 1
// Math.max(3, 5, 1, 9) returns 9
Math Methods - Random
// Math.random() - returns decimal between 0 (inclusive) and 1 (exclusive)
let randomDecimal = Math.random(); // e.g., 0.382749
// Random integer between 1 and 10
let random1to10 = Math.floor(Math.random() * 10) + 1;
// Random integer between 0 and 100
let random0to100 = Math.floor(Math.random() * 101);
// Random choice from array
let colors = ['red', 'blue', 'green'];
let randomColor = colors[Math.floor(Math.random() * colors.length)];
Special Number Values
JavaScript has special numeric values you should be aware of:
Infinity and -Infinity
// Infinity - greater than any number
let inf = Infinity;
let negInf = -Infinity;
// Operations that produce Infinity
// 1/0 = Infinity
// -1/0 = -Infinity
// Math.pow(10, 1000) = Infinity
// Check for infinity
// isFinite(100) returns true
// isFinite(Infinity) returns false
// Number.isFinite(100) returns true (more reliable)
NaN (Not-a-Number)
// NaN - result of invalid numeric operations
let invalid = parseInt("abc"); // NaN
let result = 0 / 0; // NaN
let notNum = Number("hello"); // NaN
// IMPORTANT: NaN is not equal to anything, even itself!
// NaN == NaN returns false
// NaN === NaN returns false
// Correct way to check for NaN
// isNaN(value) - has issues with type coercion
// isNaN("hello") returns true (string coerced to NaN)
// Better way - use Number.isNaN()
// Number.isNaN(NaN) returns true
// Number.isNaN("hello") returns false (no type coercion)
Number.isNaN() instead of isNaN() to check for NaN, as it doesn't perform type coercion.
Type Conversion
Converting other types to numbers is a common task:
Number() Function
// Number() - converts to number
// Number("42") returns 42
// Number("3.14") returns 3.14
// Number(true) returns 1
// Number(false) returns 0
// Number(null) returns 0
// Number(undefined) returns NaN
// Number("") returns 0
// Number("abc") returns NaN
parseInt() and parseFloat()
// parseInt() - parse string to integer
// parseInt("42") returns 42
// parseInt("42.99") returns 42 (ignores decimal)
// parseInt("0xFF", 16) returns 255 (hexadecimal)
// parseInt("hello") returns NaN
// parseInt("42px") returns 42 (stops at non-numeric)
// parseFloat() - parse string to decimal
// parseFloat("42") returns 42
// parseFloat("42.99") returns 42.99
// parseFloat("3.14e2") returns 314
// parseFloat("hello") returns NaN
// parseFloat("42.5px") returns 42.5 (stops at letter)
// Note: Always specify radix with parseInt
// parseInt("10", 10) returns 10 (base 10)
// parseInt("10", 2) returns 2 (base 2, binary)
// parseInt("FF", 16) returns 255 (base 16, hexadecimal)
Unary Plus Operator
// Unary plus (+) converts to number
// +"42" returns 42
// +"3.14" returns 3.14
// +true returns 1
// +false returns 0
// +"hello" returns NaN
// Often shorter than Number()
let str = "123";
let num1 = Number(str);
let num2 = +str; // Same result, but shorter
Best Practices
Key Takeaways
JavaScript has one number type: 64-bit floating-point
Use standard arithmetic operators and remember operator precedence
toFixed() formats decimals but returns a string
Math object provides constants and mathematical methods
Handle Infinity and NaN with Number.isFinite() and Number.isNaN()
Convert to numbers with Number(), parseInt(), or parseFloat()
Frequently Asked Questions
A number in JavaScript is a numeric data type that represents both integers and decimal values. JavaScript uses a single number type: 64-bit floating-point numbers following the IEEE 754 standard. This means integers and decimals are stored the same way internally.
parseInt() converts a string to an integer (whole number), stopping at the first non-numeric character. parseFloat() converts a string to a decimal number and includes the decimal point. For example, parseInt("42.99") returns 42, while parseFloat("42.99") returns 42.99.
NaN stands for "Not-a-Number" and represents an invalid or undefined numeric result. It results from invalid operations like parseInt("abc") or 0/0. Importantly, NaN is not equal to anything, even itself. Use Number.isNaN() to check for NaN reliably without type coercion.
Use different Math methods for different rounding: Math.round() rounds to nearest integer, Math.ceil() rounds up, Math.floor() rounds down, and Math.trunc() removes decimals. For formatting with specific decimal places, use toFixed() method (note: returns a string).
toFixed(digits) returns a string representation of a number fixed to a specific number of decimal places. For example, (3.14159).toFixed(2) returns the string "3.14". Important: it returns a string, not a number, so convert back if needed for calculations.
No, JavaScript numbers can have precision issues due to floating-point representation. For example, 0.1 + 0.2 doesn't exactly equal 0.3 in JavaScript. For financial calculations requiring high precision, use specialized libraries like Decimal.js or handle amounts in cents as integers instead of dollars with decimals.