Programming Basics
Type Conversion (Casting)
The idea, in plain English
Type conversion, also called 'casting', is like exchanging currency. The value stays meaningfully the same, but you change the FORM it's in so it works where you need it. For example, you can turn the text "9.5" into the actual number 9.5. Or you can turn the number 42 into the text "42" so you can glue it onto a sentence.
How it works
- 1Text that looks like a number, like `"9.5"`, can be converted into a real number so you can do math with it. In JavaScript, use `parseFloat`. In Python, use `float`.
- 2A number can be converted into text so you can join it with other text. In JavaScript, use `String(...)`. In Python, use `str(...)`.
- 3A number with a decimal point can be converted down to a whole number by cutting off everything after the decimal. This is called 'truncating', not rounding.
When you'd use it
Use type conversion whenever data arrives in the 'wrong' form for what you want to do with it. For example, a price typed into a form arrives as text, but you need it as a number to multiply. A score is a number, but you need it as text to display in a sentence.
Common beginner mistakes
- Trying to do math directly on text without converting it first. Most languages will either error, or glue the text together instead of adding numbers.
- Assuming converting a decimal to a whole number rounds it. It actually just chops off the decimal part, so `9.8` becomes `9`, not `10`.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Price text: 9.5
Price number: 9.5
Total: 28.50
Count as text: Item #42
Whole number from float: 9Not sure this is the right topic? See the learning paths → or where this leads →