Course outline · 0% complete

0/29 lessons0%

Course overview →

Parsing and formatting numbers

lesson 8-2 · ~9 min · 26/29

Text in, numbers out

User input and file data arrive as strings. Python used int("42") and float("3.5"). JavaScript gives you:

  • Number("42")42. Strict: the whole string must be numeric, otherwise you get NaN.
  • parseInt("42px", 10)42. Forgiving: reads leading digits and stops. The 10 means base ten, always pass it.
  • parseFloat("3.5kg")3.5. Same idea with decimals.

NaN ("not a number") is the result of failed number math. It is contagious (NaN + 1 is NaN) and weird: it is not even equal to itself. Test for it with Number.isNaN(x), never with ===.

Going the other way, toFixed formats with a fixed number of decimals: (3.14159).toFixed(2) gives "3.14". Careful: it returns a string, ready for display, not for more math.

One more classic: 0.1 + 0.2 prints 0.30000000000000004. Computers store decimals in binary, so tiny rounding errors appear. Python does the exact same thing. Format with toFixed when showing money.

Code exercise · javascript

Run it. Note the strict Number vs forgiving parseInt, the famous 0.1 + 0.2 result, and toFixed cleaning it up for display.

Code exercise · javascript

Your turn. The two prices arrived as strings. Convert both with Number, add them, and print the total formatted to exactly 2 decimal places.

Quiz

const price = (9.5).toFixed(2); What is typeof price?