Converting strings to numbers
Number('') gives 0, not NaN, so an empty amount field is read as zero, while parseInt and parseFloat silently cut the string at a foreign character. A comma is not a decimal separator in Number or parseFloat, and parseInt is always called with radix 10. For UI amounts, write a strict parser: strip spaces and the currency, replace the comma, check the format and return integer minor units.
TypeScript · JS traps
An empty amount field was read as 0 and the test «successfully» checked a zero payment. Where did the zero come from?
The amount field on a form was left empty. The test read its value, converted it through Number(raw) and compared it with zero: the check passed. In reality the empty field should have produced a validation error and the test did not notice because Number('') returns 0 and not NaN. Similar quiet conversions exist in all ways of «making a number from a string» and each one behaves differently. This lesson goes through them together and gives a recipe for reliable reading of amounts from the interface.
How it works and why. There are two families. Number(s) and unary plus apply the specification's conversion to the whole string: they strip whitespace at the edges, treat an empty string as zero and any foreign character gives NaN. parseInt and parseFloat instead read a number from the start of the string and silently drop the rest. That is historically handy for «12px» but dangerous for checks: a partly parsed string looks like a normal number.
| String | Number(s) | parseInt(s, 10) | parseFloat(s) |
|---|---|---|---|
'42' | 42 | 42 | 42 |
'' | 0 | NaN | NaN |
'12px' | NaN | 12 | 12 |
'1e3' | 1000 | 1 | 1000 |
'1,5' | NaN | 1 | 1 |
'1 000.50' | NaN | 1 | 1 |
'0x10' | 16 | 0 | 0 |
Other values are surprising too: Number(null) and Number([]) give 0, Number(undefined) gives NaN, Number('1_000') gives NaN and Number(' 42 ') gives 42. A comma is not a decimal separator in either Number or parseFloat, although in a Ukrainian interface it is exactly that.
Example: a zero instead of an error.
const raw = await page.getByTestId('amount').inputValue(); // ''
const amount = Number(raw); // 0
expect(amount).toBeGreaterThanOrEqual(0); // green
Two ways to read an amount from a field
Number(raw) / parseFloat(raw)
An empty field becomes 0, «1 250,50 ₴» becomes 1 or NaN. The test checks not what the user is shown.
A strict format parser
The string is first checked with a regular expression and an unknown format throws an error. The failure appears at the reading place and not on a wrong number later.
For amounts from the interface an explicit parser for the specific format is written: remove spaces (including the non-breaking one that Intl.NumberFormat puts between thousands; the \s class in regular expressions covers both U+00A0 and the narrow non-breaking U+202F), the currency sign, change the comma to a dot, check with a regular expression and only then convert. After that take integer minor units (see the previous lesson):
function parseUiAmount(text: string): number {
const clean = text
.replace(/\s/g, '') // \s also covers non-breaking spaces
.replace(/(₴|UAH)/, '')
.replace(',', '.');
if (!/^-?\d+(\.\d{1,2})?$/.test(clean)) {
throw new Error('Bad amount: ' + text);
}
return toMinor(clean); // minor units
}
parseUiAmount('1\u00a0250,50 ₴'); // 125050
parseUiAmount('12px'); // Error: Bad amount: 12px
A better alternative to parsing: do not convert the output to a number but compare with the expected string formatted by the same Intl.NumberFormat with the needed locale. Then the format is checked the way the user sees it.
The traps that occur most often.
['1', '2', '3'].map(parseInt); // [1, NaN, NaN]: map passes (value, index, array)
['1', '2', '3'].map(Number); // [1, 2, 3]
['1', '2', '3'].map((s) => parseInt(s, 10)); // [1, 2, 3]
map(parseInt) breaks because map passes three arguments to the callback and the second one for parseInt is the radix (radix 1 is invalid, 2 does not fit '3'). So parseInt is always called with an explicit radix of 10. Checking for NaN has its own pitfalls too:
NaN === NaN; // false
Number.isNaN('abc'); // false: no coercion, 'abc' is not the number NaN
isNaN('abc' as any); // true: coerces first (TS2345 without as any)
Number.isNaN(Number('abc')); // true
Number.isFinite('5'); // false: strict, no coercion
Number.isFinite(5 / 0); // false
Limits and alternatives. For values that come from an API a string-to-number conversion is usually not needed: if the contract says «the amount is a string with a decimal fraction» the TS type is declared that way (string) and converted to minor units with a single parser. In schema-based frameworks (zod) there is z.coerce.number(), but it works through Number() and likewise turns an empty string into 0: for amounts your own format check is better. «What the user typed» and «what is shown» should be parsed differently: typed input often contains spaces and separators, the shown value depends on the locale.
Common mistakes.
Number('')andNumber(' ')give 0: an empty field is read as a zero amount.parseIntandparseFloatsilently cut the string: «1 250,50 ₴» gives 1.parseIntwithout a radix or insidemapas a reference: a different radix than expected.x === NaNis always false; andisNaN('abc')coerces the string first.- A parser that leaves the non-breaking space: the string «1 250» does not match the regular expression because the space is not an ordinary one.
Check yourself
What will Number('12,5'), parseFloat('12,5') and Number('') return and why does it matter for a test of a Ukrainian interface?
Answer
NaN, 12 and 0. The Ukrainian locale shows a decimal fraction with a comma and JS does not consider it a separator: Number gives NaN and parseFloat silently drops the fractional part. An empty string gives 0. So you need your own parser that replaces the comma and checks the format.
Why does ['10', '10', '10'].map(parseInt) return [10, NaN, 2]?
Answer
map passes (value, index) so the second argument of parseInt becomes the radix: 0 (meaning 10), 1 (invalid, gives NaN) and 2 (binary, '10' is 2). The fix: map((s) => parseInt(s, 10)) or map(Number).
Number('') gives zero and parseInt silently cuts the string at the first invalid character. I check NaN with Number.isNaN and call parseInt with radix 10. Middle/Senior: For amounts from the interface I write a strict parser: I remove spaces (the \s class also takes non-breaking ones) and the currency, replace the comma, check with a regular expression and fail on an unknown format, and I hand the result back as integer minor units. Sometimes it is simpler to compare with a string formatted by Intl.NumberFormat of the same locale.