முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 2 · பாடம் 4 இன் 4பாடத்திட்டத்தில் 8/32~8 min
தொகுதி பாடங்கள் (4/4)

வகை மாற்றங்கள்

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:

JS
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'); // true

parseInt and parseFloat: tolerant parsers

Unlike Number(...), parseInt and parseFloat ignore the non-numeric tail of the string: they stop at the first invalid character.

JS
Number('42px'); // NaN
parseInt('42px'); // 42
parseFloat('3.14em'); // 3.14
parseInt('   12 anni'); // 12
parseInt('ciao12'); // NaN  ← must start with digits

toFixed to format numbers as strings

Seen briefly in the previous lesson: rounds to N decimals and returns a string.

JS
(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 +:

JS
Number((3.14159).toFixed(2)); // 3.14
+(3.14159).toFixed(2); // 3.14

NaN: the value that bites

NaN ("Not a Number") is produced by numeric operations that fail:

JS
Number('ciao'); // NaN
0 / 0; // NaN
parseInt('xxx'); // NaN

Characteristics:

  • it has type 'number' (yes, a "non-number" is a number)
  • it is not equal to itself: NaN === NaN is false
  • to test it use the function Number.isNaN(x)
JS
const x = Number('ciao');
x === NaN; // false (!)
Number.isNaN(x); // true

Try it

உடற்பயிற்சி#js.m2.l4.e1
முயற்சிகள்: 0ஏற்றுகிறது…

Given the string '128.95 EUR', extract the (decimal) number and round it to the nearest integer, returning it as a number. Expected: 129.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

parseFloat ignores 'EUR'; .toFixed(0) rounds to an integer as a string; Number(...) converts back to a number.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Review exercise

உடற்பயிற்சி#js.m2.l4.e2
முயற்சிகள்: 0ஏற்றுகிறது…

Given `n = Number('non un numero')`, write a single expression that evaluates to true if the result is NaN.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Use Number.isNaN, not n === NaN: NaN is not equal to itself.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்