Numbers in JavaScript

Introduction

JavaScript uses one number type (IEEE 754 double-precision) for integers, decimals, and scientific notation. This chapter explains literals, common operations, rounding pitfalls, and safe habits for money-like values. Numbers power scores, timers, pagination, and analytics in almost every app.

Prerequisites

Number Literals

javascript
// Integer, decimal, and scientific notation
const count = 42;
const ratio = 0.75;
const big = 6.02e23;
 
console.log(count, ratio, big);

Arithmetic Operators

javascript
// Basic math
const a = 10;
const b = 3;
 
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
console.log(a ** b);

Division always returns a number (often with decimals): 10 / 4 is 2.5.

Assignment Operators

javascript
// Compound assignment
let points = 100;
points += 25;
points -= 10;
points *= 2;
 
console.log(points);

Floating-Point Gotchas

Some decimals are not exact in binary floating point:

javascript
// Famous floating-point surprise
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);

Tip

Best Practice

For currency, consider storing integer cents or using libraries like decimal.js. For learning math, Number is fine; for money in production, be deliberate.

Rounding and Formatting

javascript
// toFixed returns a string with fixed decimals
const price = 19.9;
console.log(price.toFixed(2));
 
// Math helpers
console.log(Math.round(4.6));
console.log(Math.floor(4.9));
console.log(Math.ceil(4.1));
console.log(Math.max(3, 9, 2));

Parsing Strings to Numbers

User input arrives as strings—parse explicitly:

javascript
// parseInt and parseFloat
const inputA = "42";
const inputB = "3.14px";
 
console.log(Number(inputA));
console.log(parseInt(inputB, 10));
console.log(parseFloat(inputB));
 
// Number() for strict numeric conversion
console.log(Number("  7  "));
console.log(Number("abc"));

Number("abc") is NaN (Not a Number).

Checking Numbers

javascript
// NaN checks
const value = Number("oops");
console.log(Number.isNaN(value));
console.log(Number.isFinite(100));

bigint (Brief)

Very large integers can use bigint with n suffix:

javascript
// bigint for integers beyond safe Number range
const huge = 9007199254740991n;
console.log(huge + 1n);

Use bigint only when you truly need it; most apps use regular numbers.

Mini Example: Unit Converter

javascript
// Convert kilometers to miles
const km = 10;
const milesPerKm = 0.621371;
const miles = km * milesPerKm;
 
console.log(`${km} km ≈ ${miles.toFixed(2)} miles`);

FAQ

Is there an int type?

No separate integer type—number covers both 42 and 3.14.

Why use === with numbers?

Avoid coercion surprises. 0 == false is true with ==; 0 === false is false.

What is Infinity?

Result of division by zero or overflow; still type "number".

What comes next?

Booleans, null and undefined, then type conversion.