Reading a Number Off the Front of Text
In this lesson, you ported the total of the web shop’s export, where each café’s line carries its unit, and met JavaScript’s two parse functions for text that starts with a number.
- The export lists tonight’s orders as
"12kg","8kg"and"17.5kg", which add up to 37.5 kg. Python strips the unit with.removesuffix("kg")and converts the rest withfloat(). - JavaScript strings have no
.removesuffix(), andNumber("12kg")isNaN, becauseNumber()wants the whole text to be a number. parseInt()reads digits from the front of the text and ignores the rest, soparseInt("12kg")is 12. It looks like Python’sint(), but it stops at the first character that can’t be part of a whole number, soparseInt("17.5kg")is 17, with no error.- Python’s
int()refuses the same number, even from the cleaned line:int("17.5")raisesValueError: invalid literal for int() with base 10: '17.5'. Number()andparseInt()aren’t two spellings of one conversion. On"12kg",Number()givesNaNandparseInt()gives 12. On"17.5",Number()gives 17.5 andparseInt()gives 17.parseFloat()reads the decimal point and the digits after it, and stops at the first character that can’t be part of a number:parseFloat("17.5kg")is 17.5.- Unlike Python’s
float(), which raisesValueErroron"17.5kg",parseFloat()drops the unit without a word. - When text holds a whole number, such as a bag size of
"250g", giveparseInt()its radix, the number base, as Python’sint()can take:parseInt("250g", 10)gives 250, asint("250g".removesuffix("g"), 10)does in Python. The radix doesn’t make it strict: it still ignores the rest of the text. - Without a radix,
parseInt()works out the base from the text:0xmarks base 16, soparseInt("0x1A")is 26, where Python’sint("0x1A")raisesValueError. Always give the radix, so the base is the one you meant, not guessed from the text:parseInt("0x1A", 10)is 0, still a wrong number and still no error. - Watch out: to drop the decimals from a number, as Python’s
int()does, useMath.trunc(), notparseInt().parseInt()turns a number into text first, and0.0000005becomes"5e-7", soparseInt(0.0000005)is 5, whereMath.trunc()and Python’sint()give 0. - Use
parseFloat(), orparseInt(text, 10), for text that starts with a number and goes on with a unit you expect: they ignore the rest silently. To check that a paste is only a number, useNumber()andNumber.isNaN(), after checking it isn’t blank.
Here’s the port as first written, with parseInt():
const EXPORT_LINES = ["12kg", "8kg", "17.5kg"];
let totalKg = 0;
for (const line of EXPORT_LINES) {
totalKg += parseInt(line);
}
console.log(`Export total: ${totalKg} kg`);