JavaScript — Lesson 9
Number & Math Methods
Working with numbers, calculations, and formatting.
Number & Math Methods
JavaScript has built-in number types and a Math object with useful methods for calculations, rounding, and randomization.
Parsing Numbers
// parseInt: extract integer from string
parseInt("42px"); // 42
parseInt("abc"); // NaN (not a number)
parseInt("101", 2); // 5 (binary to decimal)
// parseFloat: extract decimal from string
parseFloat("3.14px"); // 3.14
// Number(): strict conversion
Number("42"); // 42
Number(""); // 0
Number("abc"); // NaN
Math Methods
Math.round(4.6); // 5 (nearest integer)
Math.floor(4.9); // 4 (round down)
Math.ceil(4.1); // 5 (round up)
Math.trunc(4.9); // 4 (remove decimals)
Min, Max & Random
Math.max(10, 5, 20); // 20
Math.min(10, 5, 20); // 5
// Random between min and max (inclusive)
function randomBetween(min, max) {
return Math.floor(
Math.random() * (max - min + 1) + min
);
}
randomBetween(1, 6); // 1-6 (dice roll)
Math.random(); // 0 to 0.999...
Formatting Numbers
// toFixed: decimal places (returns string)
3.14159.toFixed(2); // "3.14"
2.5.toFixed(0); // "3"
// toLocaleString: formatted with commas
1234567.toLocaleString(); // "1,234,567"
1234567.toLocaleString("en-US", {
style: "currency",
currency: "USD"
}); // "$1,234,567.00"
Other Useful Math
Math.PI; // 3.141592653589793
Math.abs(-5); // 5 (absolute value)
Math.pow(2, 3); // 8 (2 to the power of 3)
Math.sqrt(16); // 4 (square root)
Tip:
toFixed() returns a string. Use Number() to convert it back if you need to do more math.
Practice what you learned in the Deoit Editor — a free, browser-based code editor.
Open Editor →