Last updated

JavaScript Numbers

Definition: JavaScript has a single number type used for both whole numbers and decimals.

let a = 10;
let b = 3;
console.log(a + b);
console.log(a / b);

Example 1 — rounding and number methods

let pi = 3.14159;
console.log(pi.toFixed(2));    // "3.14" (2 decimals)
console.log(Math.round(4.6));  // 5
console.log(Math.floor(4.9));  // 4 (down)
console.log(Math.ceil(4.1));   // 5 (up)
console.log(Math.max(3, 9, 1));// 9

Example 2 — turning text into a number

User input arrives as text; convert it before doing maths:

let text = "42";
console.log(Number(text) + 1);     // 43
console.log(parseInt("10 apples"));// 10
console.log(parseFloat("3.5kg"));  // 3.5

Example 3 — NaN (Not a Number)

console.log(Number("hello"));  // NaN
console.log(10 / "abc");       // NaN

Example 4 — money with toFixed

let price = 19.99;
let qty = 3;
console.log("Total: $" + (price * qty).toFixed(2));

💡 Tip: toFixed(2) is perfect for prices and percentages.

Try it Yourself
Output

          
Ad · responsive