JavaScript Numbers: Integer and Floating-Point Literals and the Math Object
How JavaScript's single number type works: 64-bit floats for integers and fractions, every literal form (hex, binary, octal, exponents, separators), and a tour of Math: rounding (why Math.round(-2.5) is -2), min/max pitfalls, powers, logs, trig, random integers and new methods.
kvi5hnuCode Sprout team member8 min readOn this page
Most languages have several numeric types: int, long, float, double. JavaScript has just one for everyday use, number. It holds integers and fractions alike. (There's also bigint for huge integers, covered in article 13.) This article covers how numbers are written in code and the Math object you use to compute with them.
One type for every number
Every number is a 64-bit floating-point value in the IEEE 754 "double precision" format, the same format as double in Java, C and C++. That gives you:
| Property | Value | Meaning |
|---|---|---|
| Largest value | about 1.8 × 10^308 (Number.MAX_VALUE) | bigger results become Infinity |
| Smallest positive value | about 5 × 10^-324 (Number.MIN_VALUE) | smaller results become 0 |
| Exact integers | from -(2^53 - 1) to 2^53 - 1 | about ±9 quadrillion (Number.MAX_SAFE_INTEGER is 9007199254740991) |
| Precision | about 15 to 17 significant decimal digits | beyond that, digits are approximate |
So 42 and 42.0 are the same value, and there's no separate integer type. Integers within the safe range are stored exactly and behave just as you'd expect. Two places treat numbers as 32-bit integers instead: the bitwise operators (&, |, ^, ~, <<, >>, >>>, covered in part 4) and some internal operations such as array lengths.
The next two articles cover the special values (Infinity, NaN, -0) and why 0.1 + 0.2 isn't 0.3.
Writing numbers: literals
console.log(255, 255.0, 0.5, .5); // decimal: 255.0 is the same as 255
console.log(0xff, 0XFF, 0xBEEF); // hexadecimal (base 16)
console.log(0b1010, 0B101); // binary (base 2)
console.log(0o17, 0O777); // octal (base 8)
console.log(6.022e23, 1.5E-4, 2e0); // exponent: 1.5E-4 is 1.5 × 10^-4
console.log(1_000_000, 0b1111_0000, 3.141_592); // _ separators (ES2021)
console.log(-42, - 42); // the minus is an operator, not part of the literal
255 255 0.5 0.5
255 255 48879
10 5
15 511
6.022e+23 0.00015 2
1000000 240 3.141592
-42 -42
Rules worth knowing:
- Prefixes and the
eare case-insensitive (0x/0X,e/E), and hex digits can be either case. - A literal can start or end with a decimal point (
.5,5.), though0.5and5are clearer. - Numeric separators
_go only between digits: not at the start or end, not next to.ore, and not two in a row. They don't change the value; they're purely for readability. - A negative number is written with the unary minus operator,
-42. That's why-2 ** 2is aSyntaxError(is it(-2) ** 2or-(2 ** 2)?) and you must add parentheses. - Integer literals with more digits than fit precisely are rounded:
123456789012345678901234567890becomes1.2345678901234568e+29.
When a number is printed, JavaScript chooses the shortest decimal string that maps back to exactly the same value, and uses exponent notation for very large or very small numbers (from 1e21 up and below 1e-6).
The Math object
Math is a built-in object that holds mathematical constants and functions. You don't create it with new; you call its methods directly: Math.sqrt(16).
Rounding
Four functions turn fractions into integers, and they differ for negative numbers and halves:

console.log(" x round floor ceil trunc");
for (const x of [2.4, 2.5, 2.6, -2.4, -2.5, -2.6]) {
const row = [Math.round(x), Math.floor(x), Math.ceil(x), Math.trunc(x)];
console.log(String(x).padStart(4), row.map(n => String(n).padStart(5)).join(""));
}
x round floor ceil trunc
2.4 2 2 3 2
2.5 3 2 3 2
2.6 3 2 3 2
-2.4 -2 -3 -2 -2
-2.5 -2 -3 -2 -2
-2.6 -3 -3 -2 -2
| Function | Rule |
|---|---|
Math.floor(x) | down, toward -∞ |
Math.ceil(x) | up, toward +∞ |
Math.trunc(x) | toward zero: just drops the fraction (ES2015) |
Math.round(x) | to the nearest integer; an exact half goes up, toward +∞ |
That last rule surprises people: Math.round(-2.5) is -2, not -3, because "up" means toward positive infinity. If you need "half away from zero", write Math.sign(x) * Math.round(Math.abs(x)).
To round to a number of decimal places, a common trick is to scale, round and scale back:
const price = 19.98765;
console.log(Math.round(price * 100) / 100); // 2 decimal places, as a number
console.log(price.toFixed(2)); // 2 decimal places, as a string
console.log(Math.round(1.005 * 100) / 100); // expected 1.01!
console.log((1.005).toFixed(2));
19.99
19.99
1
1.00
Neither gave the "expected" 1.01, because the literal 1.005 is actually stored as 1.00499999999999989... Floating-point representation is the reason; article 12 explains it and shows the safe ways to handle money.
Smallest and largest
console.log(Math.max(4, 9, 2), Math.min(4, 9, 2));
const scores = [71, 88, 64];
console.log(Math.max(...scores)); // spread an array into arguments
console.log(Math.max(3, "7", 1)); // arguments are converted to numbers
console.log(Math.max(1, NaN, 3)); // any NaN makes the result NaN
console.log(Math.max(), Math.min()); // no arguments: -Infinity and Infinity
9 2
88
7
NaN
-Infinity Infinity
Two traps hide here. Math.max() with an empty array spread into it returns -Infinity, not undefined or an error. And spreading a huge array into the arguments can overflow the call stack: on current Node.js versions, Math.max(...arrayOf200000Items) throws RangeError: Maximum call stack size exceeded. For large arrays, use a loop or reduce:
const biggest = values.reduce((max, v) => (v > max ? v : max), -Infinity);
Powers, roots and logarithms
| Call | Result | Notes |
|---|---|---|
Math.pow(2, 10) or 2 ** 10 | 1024 | ** is the operator form (ES2016) |
Math.sqrt(81) | 9 | square root; negative input gives NaN |
Math.cbrt(-27) | -3 | cube root, works for negatives ((-27) ** (1/3) is NaN) |
Math.hypot(6, 8) | 10 | √(6² + 8²): distance, avoids overflow |
Math.exp(1) | 2.718281828459045 | e^x |
Math.log(Math.E) | 1 | natural logarithm |
Math.log2(8), Math.log10(1000) | 3, 3 | base-2 and base-10 logarithms |
Math.log1p(x), Math.expm1(x) | accurate log(1 + x) and e^x - 1 for tiny x |
Trigonometry
Math.sin, cos, tan, asin, acos, atan and the hyperbolic versions (sinh, cosh, tanh, asinh...) all work in radians, not degrees. Convert with degrees * Math.PI / 180. Math.atan2(y, x) returns the angle of the point (x, y), handling all four quadrants, which plain atan(y / x) can't do.
const toRadians = deg => deg * Math.PI / 180;
const toDegrees = rad => rad * 180 / Math.PI;
console.log(Math.sin(toRadians(30))); // about 0.5
console.log(toDegrees(Math.atan2(1, 1))); // the point (1, 1) is at 45°
console.log(toDegrees(Math.atan2(-1, -1))); // (-1, -1) is at -135°
console.log(Math.sin(Math.PI)); // not exactly 0: PI itself is approximate
0.49999999999999994
45
-135
1.2246467991473532e-16
Constants and other helpers
- Constants:
Math.PI,Math.E,Math.SQRT2,Math.SQRT1_2,Math.LN2,Math.LN10,Math.LOG2E,Math.LOG10E. Math.abs(x)(absolute value) andMath.sign(x)(-1, 0 or 1; also -0 and NaN for those inputs).Math.fround(x)rounds to the nearest 32-bit float, andMath.f16round(x)(ES2025) to the nearest 16-bit float. They're useful with graphics and machine-learning data stored inFloat32ArrayorFloat16Array.Math.imul(a, b)multiplies as 32-bit integers, andMath.clz32(x)counts leading zero bits. They're mostly used by compilers that target JavaScript.Math.sumPrecise(values)(ES2026) adds a whole list of numbers without accumulating rounding errors. Article 12 shows when that matters.
Random numbers
Math.random() returns a number from 0 (inclusive) up to but not including 1. To get a random integer in a range:
function randomInt(min, max) { // min and max both inclusive
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const rolls = Array.from({ length: 1000 }, () => randomInt(1, 6));
console.log(Math.min(...rolls), Math.max(...rolls)); // always within 1..6
console.log(rolls.every(Number.isInteger));
1 6
true
Use floor, not round: Math.round(Math.random() * 5) + 1 makes 1 and 6 half as likely as the other faces.
Dates are numbers too
Times are commonly stored as numbers: Date.now() returns the number of milliseconds since the start of 1 January 1970 UTC (the Unix epoch), and subtracting two such timestamps gives an elapsed time. The Date class, and its modern replacement Temporal, are covered in part 11.
Common questions
How do I check whether a number is an integer?
Number.isInteger(x). It returns true for 5 and 5.0 (the same value), and false for 5.5, NaN, Infinity and non-numbers. To also require that the integer is exactly representable, use Number.isSafeInteger(x).
Is Math.pow slower than **?
In current engines they're the same speed for practical purposes. ** is shorter and also works with BigInt, which Math.pow doesn't. Note that ** is right-associative: 2 ** 3 ** 2 is 2 ** 9, which is 512.
Why is Math.sin(Math.PI) not 0?
Math.PI is the nearest double to π, not π itself, so its sine is a tiny number (about 1.2 × 10^-16) instead of 0. Compare results of trigonometry with a tolerance rather than with ===.
Can I add my own functions to Math?
Technically yes (Math.clamp = ...), but don't: future standards may add a method with the same name and different behavior, which has broken real websites in the past. Write ordinary functions or modules instead.
Summary
- JavaScript's
numberis a 64-bit IEEE 754 float. Integers are exact up to 2^53 - 1; beyond that, usebigint. - Literals: decimal,
0x,0b,0o, exponents withe, and_separators between digits. Negative numbers use the unary minus operator. Math.floor,ceil,truncandrounddiffer for negatives;Math.roundsends halves toward +∞ (Math.round(-2.5)is -2).Math.max()/min()with no arguments give-Infinity/Infinity. Avoid spreading huge arrays into them.- Trig functions use radians.
Math.randomisn't secure; usecrypto.getRandomValuesorcrypto.randomUUID.
Practice Questions
What do Math.round(-0.5), Math.round(0.5) and Math.trunc(-0.9) return?
Answer
-0, 1 and -0. Math.round(-0.5) rounds the half toward +∞, giving negative zero (displayed as -0 in Node and as 0 in most other output). Math.trunc(-0.9) drops the fraction and keeps the sign, also giving -0.
Write an expression for a random even integer from 0 to 100 inclusive.
Answer
Math.floor(Math.random() * 51) * 2. There are 51 even numbers from 0 to 100, so pick a random integer from 0 to 50 and double it.
const temps = []; What is Math.max(...temps), and how would you make "no data" explicit?
Answer
-Infinity, because spreading an empty array calls Math.max() with no arguments. Check first: temps.length ? Math.max(...temps) : null (or undefined), so the caller can tell "no data" from a real temperature.
What is the value of 0b11 + 0o11 + 0x11?
Answer
3 + 9 + 17 = 29.
Why is Math.round(Math.random() * 6) a bad way to simulate a die?
Answer
It produces 0 to 6, seven possible values, and the end values 0 and 6 each have half the probability of the others, because only half an interval rounds to them. Use Math.floor(Math.random() * 6) + 1.
Previous: JavaScript Types and Values: Primitives, Objects and the typeof Operator
Next: Infinity, NaN and Negative Zero in JavaScript: Special Number Values Explained

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.