Quiz: Can you count on JavaScript?
Know your parseInt from parseFloat?
Welcome to my JavaScript Numbers Challenge!
This quiz will test your knowledge all things Numbers in JS, parseInt, parseFloat, and BigInt too!.
We’ll cover parsing numeric expressions - in varying bases, handling floating-point precision, and understanding the quirks of JavaScript’s number system.
It’s only numbers, how hard can it be? 🤓
0.1 + 0.2 === 0.3Due to floating-point precision errors, 0.1 + 0.2 does not exactly equal 0.3. Due to the way floating-point numbers are stored in memory, the result is 0.30000000000000004. The IEEE 754 standard for handling floating-point arithmetic is the culprit, it can’t represent some numbers exactly. This is a common issue in all programming languages. Eventually you’ll run into a infinitely repeating decimal, and no matter the language - the computer simply has to stop chasing infinitely repeating digits.
Some languages like Python and Java have Decimal or BigDecimal to handle this, but it’s not built into JavaScript. You can use libraries like big.js or decimal.js to handle these cases.
(Note: Some languages are designed to handle fractions, imaginary numbers, etc at a higher logical level, preserving literal expressions. But they still have to deal with the same floating-point precision issues at the hardware level.)
What might this do?
5..toFixed(2).toFixed(2) returns a string representation of 5 with two decimal places, so the result is "5.00".
The double dot (5..toFixed(2)) is a ‘trick’ to access Number Literals’ Object Model.
[24, 'One', 42].map(parseInt)The second argument to parseInt (the radix) aligns with the array methods’ index argument. This leads to unexpected results, as parseInt("One", 1) returns NaN due to the invalid input.
The first element, 24, is parsed as 24 in base 0 (auto-detect), so it remains 24. The second element, 'One', is parsed as NaN in base 1. The third element, 42, is parsed using base 2. In base 2, '42' is NaN, so the result is [24, NaN, NaN].
This is a common gotcha with parseInt and map. If you want to parse an array of strings to numbers, use .map(Number) for whole-string numeric conversion, or .map(x => parseInt(x, 10)) for base-10 integer-prefix parsing. Those operations have different parsing semantics; choose the one you intend.
Comparison Table
| Function | parseInt | parseFloat | Number | BigInt |
|---|---|---|---|---|
| Ignores Whitespace | ✅ | ✅ | ✅ | ✅ |
.map(FN) | ❌ | ☑️ | ✅ | ✅ |
| Supports Radix Arg | ✅ | ❌ | ❌ | ❌ |
| Binary/Octal/Hex prefixes in strings | Hex 0x only; 0b/0o are not inferred | ❌ | ✅ | ✅ |
Invalid chars 42 oh no | 42 | 42 | NaN | SyntaxError |
How did you do? 🧐
Are you looking for a rest after so much binary?
Pftt, remember: break after skills!
Hit my gym to crush some more challenges! 💪
