Parsing numbers
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Introduction to parseInt()
Sometimes you have a number stored as a string (like "42"), but you need to use it as an actual number to do math with it. That's where parseInt() comes in!
parseInt() is a function that converts a string into an integer (a whole number without decimals).
// String containing a number
let levelString = "25";
console.log(typeof levelString); // "string"
// Convert it to a number with parseInt()
let levelNumber = parseInt(levelString);
console.log(levelNumber); // 25
console.log(typeof levelNumber); // "number"
// Now we can do math!
let nextLevel = levelNumber + 1;
console.log("Next level: " + nextLevel); // 26Notice how "25" (a string) becomes 25 (a number). Without parseInt(), trying to add 1 to "25" would give you "251" (string concatenation), not 26!
Why is it called parseInt?
The name comes from "parse" (analyze and convert) and "int" (short for integer, which is a whole number).
Exercise 2 — What does parseInt() return?
What will the following code output?
let codemonHP = "150";
let parsedHP = parseInt(codemonHP);
console.log(parsedHP);Hint : Remember: parseInt() converts a string containing a number into an actual number type. The value itself doesn't change, just its type.
Exercise 3 — Using parseInt()
Complete the code to convert the string damage into a number and calculate total damage.
Hint : Use parseInt() to convert a string to an integer. Pass the string variable as an argument inside the parentheses.
Exercise 4 — Introduction to parseFloat()
What if your number has decimals? Like "3.14" or "99.9"? That's where parseFloat() comes in!
parseFloat() works just like parseInt(), but it keeps the decimal part of the number instead of removing it.
let weightString = "12.5";
// Using parseInt() - LOSES the decimal!
let weightInt = parseInt(weightString);
console.log("With parseInt: " + weightInt); // 12
// Using parseFloat() - KEEPS the decimal!
let weightFloat = parseFloat(weightString);
console.log("With parseFloat: " + weightFloat); // 12.5
// Perfect for calculations with decimals
let doubleWeight = weightFloat * 2;
console.log("Double weight: " + doubleWeight); // 25See the difference? parseInt() gives you 12 (just the whole part), while parseFloat() gives you 12.5 (the complete number).
When to use which?
Use parseInt() when you only need whole numbers (like levels, counts). Use parseFloat() when you need precision with decimals (like weights, percentages, prices).
Exercise 5 — parseInt vs parseFloat
What will this code output?
let priceString = "19.99";
let price = parseInt(priceString);
console.log(price);Hint : Think about what parseInt() does with decimal numbers. Does it round, or does it do something else?
Exercise 6 — Calculate with parseFloat()
Complete the code to convert a Codémon's attack multiplier and calculate boosted damage.
Hint : Since the multiplier has a decimal point, you need the function that preserves decimals. Then multiply to boost the damage.
Exercise 7 — Understanding NaN and Edge Cases
What happens when you try to parse something that's not a number? You get a special value called NaN (which stands for "Not a Number").
// These return NaN
console.log(parseInt("hello")); // NaN
console.log(parseFloat("Aquachu")); // NaNSomething interesting tho, if the string starts with numbers, both functions will parse as much as they can until they hit something that isn't a number.
console.log(parseInt("123abc")); // 123 (stops at first non-digit)
console.log(parseFloat("45.67xyz")); // 45.67 (stops at first invalid char)
// Starting with non-number = NaN
console.log(parseInt("abc123")); // NaNChecking for NaN
You can use isNaN() to check if something is NaN: isNaN(parseInt("hello")) returns true. This is useful to validate if parsing worked!
Exercise 8 — Match String to Parsed Result
Match each parseInt() or parseFloat() operation with its result.
parseInt("50")parseFloat("3.14")parseInt("99.9")parseInt("L42")parseFloat("7.5kg")Exercise 9 — Codémon Stats Parser
Time to practice! You received Pyrochu's stats as strings and need to convert them to numbers for calculations.
Your mission:
1. Parse the level as an integer
2. Parse the weight as a float
3. Parse the attack power as an integer
4. Calculate the total power: (level * 2) + attackPower
5. Log all the converted values and the total power
Expected output:
Level: 28
Weight: 15.3
Attack Power: 65
Total Power: 121// Pyrochu's stats as strings
let levelString = "28";
let weightString = "15.3";
let attackString = "65";
// Code here