JavaScript Number Tricks Every Developer Should Know
These one-liners will make your code shorter, faster, and cleaner.
Parsing Numbers
// ❌ Verbose ways:
parseInt('42', 10); // 42 (always specify radix!)
parseFloat('3.14'); // 3.14
Number('42'); // 42
// ✅ Quick tricks:
+'42'; // 42 (unary plus)
'3.14' * 1; // 3.14 (multiply by 1)
'42' | 0; // 42 (bitwise OR — only for integers ≤ 2^31)
~~'42'; // 42 (double bitwise NOT)
Rounding
const num = 3.7;
Math.round(num); // 4 (nearest)
Math.floor(num); // 3 (down)
Math.ceil(num); // 4 (up)
Math.trunc(num); // 3 (toward zero)
// ✅ One-liner tricks:
num | 0; // 3 (truncates to int32)
~~num; // 3 (same)
num >> 0; // 3 (same)
// Round to N decimal places:
+num.toFixed(2); // 3.70 (returns string, + converts back)
Math.round(num * 100) / 100; // 3.70 (returns number)
// Round to nearest 5:
Math.round(num / 5) * 5; // 5
Clamping (Min/Max)
const num = 50;
const min = 0;
const max = 100;
// ❌ Long way:
Math.min(Math.max(num, min), max);
// ✅ Shorter:
Math.clamp?.(num, min, max) ?? Math.min(Math.max(num, min), max);
// Note: Math.clamp is ES2024+, may need polyfill
// Clamp between 0-255 (for colors):
(0).toString(); // "0"
Random Numbers
// Random integer between min and max (inclusive):
const randomInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
randomInt(1, 10); // e.g., 7
randomInt(100, 200); // e.g., 153
// Random item from array:
const items = ['a', 'b', 'c', 'd'];
items[Math.random() * items.length | 0]; // e.g., 'c'
// Shuffle array (Fisher-Yates):
const shuffle = arr => {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.random() * (i + 1) | 0;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
};
shuffle([1, 2, 3, 4, 5]); // [3, 1, 5, 2, 4] (random order)
// Random hex color:
'#' + Math.random().toString(16).slice(2, 8).padEnd(6, '0');
// "#a3f82c"
// Random boolean:
Math.random() < 0.5; // true or false
// Random UUID-like string:
crypto.randomUUID(); // Native browser/Node method!
// "1b9d6bcd-bbfd-4b30-8b5d-5a0f0c3e4c7d"
Number Formatting
const bigNum = 1234567.89;
// Currency:
bigNum.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
// "$1,234,567.89"
bigNum.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' });
// "¥1,234,568"
// Percentage:
(0.854).toLocaleString('en-US', { style: 'percent' });
// "85%"
// Compact notation (1.2K, 3.4M):
bigNum.toLocaleString('en-US', { notation: 'compact' });
// "1.2M"
// With commas:
bigNum.toLocaleString(); // "1,234,567.89"
// Fixed decimals:
bigNum.toFixed(2); // "1234567.89"
bigNum.toPrecision(4); // "1.235e+6"
// Bytes formatting:
function formatBytes(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toFixed(i ? 1 : 0) + sizes[i];
}
formatBytes(0); // "0 B"
formatBytes(1024); // "1 KB"
formatBytes(1048576); // "1 MB"
formatBytes(1073741824); // "1 GB"
formatBytes(1536); // "1.5 KB"
Unit Conversions
// Temperature:
const cToF = c => c * 9/5 + 32;
const fToC = f => (f - 32) * 5/9;
// Time:
const msToMin = ms => Math.floor(ms / 60000);
const secToHms = s => new Date(s * 1000).toISOString().substr(11, 8);
secToHms(3661); // "01:01:01"
// Distance:
const kmToMi = km => km * 0.621371;
const miToKm = mi => mi * 1.60934;
// Degrees/Radians:
const degToRad = deg => deg * (Math.PI / 180);
const radToDeg = rad => rad * (180 / Math.PI);
Validation
// Is it a valid number?
Number.isFinite(42); // true
Number.isFinite(Infinity); // false
Number.isFinite(NaN); // false
Number.isFinite('42'); // false (use isFinite for type coercion)
// Is it an integer?
Number.isInteger(42); // true
Number.isInteger(3.14); // false
// Is it a safe integer? (≤ 2^53 - 1)
Number.isSafeInteger(Number.MAX_SAFE_INTEGER); // true
Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1); // false
// Check if NaN (the ONLY value that's not equal to itself):
const isNaN = val => val !== val; // No need for Number.isnan!
// Or use:
Object.is(NaN, NaN); // true (also handles -0 vs +0)
Math Tricks
// Power of 2?
const isPowerOf2 = n => (n & n - 1) === 0 && n !== 0;
isPowerOf2(8); // true
isPowerOf2(10); // false
// Even/Odd?
const isEven = n => (n & 1) === 0;
const isOdd = n => (n & 1) === 1;
// Absolute value without Math.abs:
const abs = n => (n ^ (n >> 31)) - (n >> 31); // For 32-bit ints
// Or just use Math.abs(n) 😄
// Min/Max of multiple values:
Math.min(1, 5, 3, 9, 2); // 1
Math.max(1, 5, 3, 9, 2); // 9
// Min/Max from array:
Math.min(...[1, 5, 3, 9]); // 1 (warning: stack overflow for huge arrays!)
// Safe way:
Array.prototype.min = function() { return Math.min.apply(null, this); };
[1, 5, 3, 9].min(); // 1
// Average:
const avg = arr => arr.reduce((a, b) => a + b, 0) / arr.length;
avg([1, 2, 3, 4, 5]); // 3
// Median:
const median = arr => {
const sorted = [...arr].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
};
median([1, 2, 3, 4, 5]); // 3
median([1, 2, 3, 4]); // 2.5
// Sum:
const sum = arr => arr.reduce((a, b) => a + b, 0);
sum([1, 2, 3, 4, 5]); // 15
BigInt (For Really Big Numbers)
// Regular numbers lose precision above 2^53:
9007199254740992 + 1 === 9007199254740992; // true! (wrong!)
// BigInt to the rescue:
BigInt('9007199254740992') + 1n === 9007199254740993n; // true!
const bigNum = 9007199254740993n;
bigNum.toString(); // "9007199254740993"
// Can't mix with regular numbers:
100n + 50; // TypeError!
100n + BigInt(50); // 150n ✅
// Useful for: IDs, timestamps, crypto, money calculations
What's your favorite number trick? Share it below!
Follow @armorbreak for more JavaScript content.
Top comments (0)