Note Number() is stricter -- rejects partially numeric strings. parseInt() stops at the first non-numeric character. Always pass the radix to parseInt() to avoid octal surprises.
parse numberstring to numberparseIntparseFloatconvert to number
Note trunc() simply removes decimals (towards zero). floor() rounds towards negative infinity. They differ for negative numbers: floor(-3.2) = -4 but trunc(-3.2) = -3.
round numberfloorceiltruncateround downround up
Formatting Decimals
syntax
num.toFixed(digits)
num.toPrecision(precision)
example
const total = 29.5;
console.log(total.toFixed(2)); // "29.50"
console.log((0.1 + 0.2).toFixed(2)); // "0.30"const big = 123456.789;
console.log(big.toPrecision(6)); // "123457"
Note toFixed() returns a STRING, not a number. Wrap in Number() or use + to convert back: +total.toFixed(2)
format decimaltoFixeddecimal placesformat currencynumber to string
Random Numbers
syntax
Math.random() // [0, 1)
example
// Random float between 0 and 1
console.log(Math.random());
// Random integer from min to max (inclusive)function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 100));
Note Math.random() is NOT cryptographically secure. For tokens or passwords, use crypto.getRandomValues() or crypto.randomUUID().
random numbergenerate randomrandom integerMath.random