Module lessons (4/4)
Type conversions
All the time you need to transform the type of a value: the value of
an HTML input arrives as a string even if it represents a number, an API
returns strings to format, you need to log an object as text. JS offers
three families of conversions: explicit, dedicated parsers, and (to be
avoided) implicit ones.
Explicit conversions
These are the clearest and should be your default:
Number('42'); // 42
Number('3.14'); // 3.14
Number(''); // 0 ← careful
Number(' 10 '); // 10 (spaces are ignored)
Number('ciao'); // NaN ← does not represent a number
String(42); // '42'
String(true); // 'true'
String(null); // 'null'
String(undefined); // 'undefined'
Boolean(1); // true
Boolean(0); // false
Boolean(''); // false
Boolean('abc'); // trueparseInt and parseFloat: tolerant parsers
Unlike Number(...), parseInt and parseFloat ignore the non-numeric
tail of the string: they stop at the first invalid character.
Number('42px'); // NaN
parseInt('42px'); // 42
parseFloat('3.14em'); // 3.14
parseInt(' 12 anni'); // 12
parseInt('ciao12'); // NaN ← must start with digitstoFixed to format numbers as strings
Seen briefly in the previous lesson: rounds to N decimals and returns a string.
(3.14159).toFixed(2); // '3.14'
(1).toFixed(2); // '1.00'To convert it back to a number use the Number(...) prefix or the unary
+:
Number((3.14159).toFixed(2)); // 3.14
+(3.14159).toFixed(2); // 3.14NaN: the value that bites
NaN ("Not a Number") is produced by numeric operations that fail:
Number('ciao'); // NaN
0 / 0; // NaN
parseInt('xxx'); // NaNCharacteristics:
- it has type
'number'(yes, a "non-number" is a number) - it is not equal to itself:
NaN === NaNisfalse - to test it use the function
Number.isNaN(x)
const x = Number('ciao');
x === NaN; // false (!)
Number.isNaN(x); // trueTry it
Given the string '128.95 EUR', extract the (decimal) number and round it to the nearest integer, returning it as a number. Expected: 129.
Show hint
parseFloat ignores 'EUR'; .toFixed(0) rounds to an integer as a string; Number(...) converts back to a number.
Solution available after 3 attempts
Review exercise
Given `n = Number('non un numero')`, write a single expression that evaluates to true if the result is NaN.
Show hint
Use Number.isNaN, not n === NaN: NaN is not equal to itself.
Solution available after 3 attempts