JavaScript Numbers and Dates - Exercise 2
parseInt() reads an integer from the start of a string and stops when the input stops looking valid, while Number() tries to convert the entire value and returns NaN if the whole conversion fails.
console.log(parseInt('42px', 10));
console.log(Number('42px'));Pass radix 10 when parsing ordinary decimal text so the intended base is explicit. This avoids ambiguity and makes the code's behavior clear to readers.
const value = parseInt('101', 10);
console.log(value);parseFloat() reads a decimal number from the beginning of a string and stops at the first character it cannot parse. Use it for values such as "19.75px", but use Number() when the whole string must be valid.
console.log(parseFloat('19.75px'));
console.log(parseFloat('3.14'));Math.abs() returns a number's distance from zero, removing a negative sign when necessary. Positive values and zero are returned unchanged, which makes it useful for differences and error magnitudes.
console.log(Math.abs(-12));
console.log(Math.abs(12));Math.max() accepts separate numeric arguments rather than an array. Spread the array at the call site so each element becomes one argument, then the largest value is returned.
const scores = [14, 22, 9];
console.log(Math.max(...scores));With no arguments, Math.min() returns Infinity, the identity value for finding a minimum. Any supplied number is smaller than it, so the first real value replaces it.
console.log(Math.min());Math.round() returns the nearest integer, using the fractional part to choose between the two surrounding integers. A fractional part of exactly 0.5 rounds toward positive infinity.
console.log(Math.round(4.4));
console.log(Math.round(4.6));JavaScript numbers use binary floating-point arithmetic, so some decimal values cannot be represented exactly. For money, it is safer to store values as the smallest unit, such as cents.
console.log(0.1 + 0.2);
const totalCents = 199 + 299;
console.log(totalCents / 100);It helps when comparing floating-point results that should be equal mathematically but differ by a tiny rounding error.
const isClose = Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON;
console.log(isClose);Use Math.max() to apply the lower bound and Math.min() to apply the upper bound.
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}