In JavaScript, information often comes as text, also called strings. But sometimes you need to do math with that information. This tutorial will teach you how to use `parseInt()` and `parseFloat()` to change strings into numbers, so you can perform calculations correctly.
parseInt(), parseFloat()
parseInt(), parseFloat()
In JavaScript, information often comes as text, also called strings. For example, when you type a number into a web form, JavaScript sees it as a string. But to do math with that number, you need to change it into a true number type. This process is called type conversion.
What is Type Conversion?
Type conversion is when you change data from one type (like a string) to another type (like a number) in your code.
parseInt() for Whole Numbers
The parseInt() function helps you turn a string into a whole number, also called an integer.
parseFloat() for Decimals
The parseFloat() function helps you turn a string into a number that can have decimal points.
Reading from the Start
Both functions read characters from the beginning of a string until they find something that is not a number.
Important for User Input
These functions are very useful when you get numbers from users, as user input is always a string.
Converting Strings to Numbers
Converting Strings to Numbers
Imagine you have a piece of text like "123". If you want to add 10 to it, JavaScript will treat "123" as text, not a number. So "123" + 10 would become "12310", which is not what you want. You need to convert "123" into the number 123 first.
1// We have a string that looks like a number2let priceText = "150";3console.log(typeof priceText); // This will show 'string'45// Use parseInt() to change the string into a whole number6// The '10' tells it to use base 10 (our normal counting system)7let priceNumber = parseInt(priceText, 10);8console.log(typeof priceNumber); // This will now show 'number'9console.log(priceNumber + 20); // Now we can do math: 150 + 20 = 170
Always Use Radix 10 with parseInt()!
When using parseInt(), always add , 10 as the second part. This tells JavaScript to convert the number using our normal base-10 system. If you don't, JavaScript might guess, and sometimes it can guess wrong, especially with numbers starting with 0.
How parseInt() and parseFloat() Work
How parseInt() and parseFloat() Work
Both parseInt() and parseFloat() start reading a string from its very first character. They keep reading, character by character, as long as they see valid numbers (digits 0-9). parseFloat() also understands a single decimal point. As soon as they hit any character that is not a number or a decimal point (for parseFloat), they stop and give you the number they've found so far.
1// We have a string that includes a decimal and some text2let measurementText = "3.14meters";3console.log(typeof measurementText); // This will show 'string'45// Use parseFloat() to change the string into a decimal number6let measurementNumber = parseFloat(measurementText);7console.log(typeof measurementNumber); // This will now show 'number'8console.log(measurementNumber); // Output: 3.14910// What happens if the number is at the end or in the middle?11let anotherText = "Size: 25px";12let badParse = parseInt(anotherText, 10);13console.log(badParse); // Output: NaN (Not a Number) because it starts with 'S'1415let yetAnotherText = "Width is 100.5 units";16let alsoBadParse = parseFloat(yetAnotherText);17console.log(alsoBadParse); // Output: NaN (Not a Number) because it starts with 'W'
// Using Number() or unary plus (+) on strings with extra textlet valueWithUnit = "123px";let num1 = Number(valueWithUnit); // Results in NaNlet num2 = +valueWithUnit; // Results in NaNconsole.log(num1); // NaNconsole.log(num2); // NaN
// Using parseInt() or parseFloat() to extract the numberlet valueWithUnit = "123px";let num1 = parseInt(valueWithUnit, 10); // Results in 123let priceWithCurrency = "$45.99";let num2 = parseFloat(priceWithCurrency); // Results in NaN (starts with '$')let tempReading = "25.7C";let num3 = parseFloat(tempReading); // Results in 25.7console.log(num1); // 123console.log(num2); // NaN (parseFloat stops at '$')console.log(num3); // 25.7
Different Ways to Convert
Different Ways to Convert
Besides parseInt() and parseFloat(), there are other ways to turn a string into a number. You can use the Number() function or a shorthand called the unary plus operator (+). These methods work differently from parseInt() and parseFloat().
// Unary Plus (+) and Number() constructorlet str1 = "123";let num1 = +str1; // Converts "123" to 123let str2 = "3.14";let num2 = Number(str2); // Converts "3.14" to 3.14let str3 = "123px";let num3 = +str3; // Converts to NaN (Not a Number)console.log(num1); // 123console.log(num2); // 3.14console.log(num3); // NaN
// parseInt() and parseFloat()let str1 = "123";let num1 = parseInt(str1, 10); // Converts "123" to 123let str2 = "3.14";let num2 = parseFloat(str2); // Converts "3.14" to 3.14let str3 = "123px";let num3 = parseInt(str3, 10); // Converts "123px" to 123console.log(num1); // 123console.log(num2); // 3.14console.log(num3); // 123
// Unary Plus (+) and Number() constructorlet str1 = "123";let num1 = +str1; // Converts "123" to 123let str2 = "3.14";let num2 = Number(str2); // Converts "3.14" to 3.14let str3 = "123px";let num3 = +str3; // Converts to NaN (Not a Number)console.log(num1); // 123console.log(num2); // 3.14console.log(num3); // NaN
// parseInt() and parseFloat()let str1 = "123";let num1 = parseInt(str1, 10); // Converts "123" to 123let str2 = "3.14";let num2 = parseFloat(str2); // Converts "3.14" to 3.14let str3 = "123px";let num3 = parseInt(str3, 10); // Converts "123px" to 123console.log(num1); // 123console.log(num2); // 3.14console.log(num3); // 123
When to Choose Which Method
Use + or Number() when you are sure the string contains only a number, with no extra characters. Use parseInt() or parseFloat() when the string might start with a number but has other text after it, like "100px" or "5.5kg".
Using Parsers in Real Web Projects
Using Parsers in Real Web Projects
One of the most common places you'll use parseInt() and parseFloat() is when you get information from a user on a website. When a user types a number into an input box, JavaScript always gets that value as a string. You need to convert it before you can do any calculations.
Get User Input
First, imagine you have an input box on your webpage where a user types a number. You would get this value using JavaScript.
1let userInput = "25"; // This would come from an input field like document.getElementById('myInput').value;
Parse the String to a Number
Next, use parseInt() or parseFloat() to convert the string. If the user typed "25.5", you would use parseFloat() to keep the decimal.
1let quantity = parseInt(userInput, 10); // If user types "25"2let price = parseFloat("10.99"); // If user types "10.99"
Perform Calculations
Now that you have real numbers, you can do math with them. You can add, subtract, multiply, or divide.
1let totalCost = quantity * price; // Example: 25 * 10.99
Display the Result
Finally, you might want to show this calculated result back to the user on the webpage.
1console.log("Your total is: $" + totalCost.toFixed(2)); // Display with 2 decimal places
What Happens if You Don't Parse?
If you forget to parse a string from user input, your math operations will go wrong. For example, if quantity is "5" (a string) and price is 10 (a number), quantity * price would result in NaN (Not a Number), because you can't multiply a string by a number in this way.
Quick Reference for parseInt() and parseFloat()
Quick Reference for parseInt() and parseFloat()
| Feature | `parseInt()` | `parseFloat()` |
|---|---|---|
| Converts to | Whole numbers (integers) | Decimal numbers (floating-point) |
| Handles decimals | Ignores anything after a decimal point | Reads a single decimal point |
| Radix (Base) | Requires a radix (e.g., `, 10`) for reliable results | Does NOT use a radix |
| Stops at | First non-digit character (except leading sign) | First non-digit character (except leading sign or first decimal) |
| Example | `parseInt("10.5", 10)` → `10` | `parseFloat("10.5px")` → `10.5` |
Test Your Knowledge
Test Your Knowledge
What will parseInt("25.75 degrees", 10) return?
Which of these will result in 3.14?
What is the output of parseInt("Hello 123", 10)?
Why is it important to include the radix (e.g., , 10) when using parseInt()?
Quick Reference
Quick Reference
- 1Type Conversion — Changing data from one type (like string) to another (like number) is called type conversion.
- 2
parseInt()— This function turns a string into a whole number, often used for things like counting items. - 3
parseFloat()— This function turns a string into a number that can have decimal points, useful for measurements or money. - 4Radix (Base 10) — Always use
parseInt(myString, 10)to make sure JavaScript converts the number correctly using our standard system. - 5Stops at Non-Numbers — Both functions read from left to right and stop as soon as they see a character that isn't part of a number.
- 6
NaNResult — If the string does not start with a number (or a sign like+or-), both functions will returnNaN(Not a Number). - 7User Input — Remember that all data from web forms comes in as strings, so you almost always need to parse it before doing math.
- 8
Number()and Unary Plus (+) — These are other ways to convert strings to numbers, but they only work if the string contains only a valid number. - 9Extracting Numbers —
parseInt()andparseFloat()are best when you need to pull a number out of a string that has other text, like "100px". - 10Practical Use — Parsing is critical for calculations, setting sizes, or any operation where numbers from text are needed.
Learn `Number()`
Explore the Number() constructor and its differences from parseInt() and parseFloat() for type conversion.
Understand `isNaN()`
Learn how to check if a value is NaN using isNaN() to handle invalid number conversions gracefully.
Explore Type Coercion
Dive deeper into how JavaScript automatically converts types in different situations, known as type coercion.
Handle Form Input
Practice getting values from HTML forms and converting them to numbers for calculations.
You've Mastered String-to-Number Conversion!
Great job! You now understand how to use parseInt() and parseFloat() to turn strings into usable numbers. This skill is fundamental for building interactive web applications and handling user input correctly. Keep practicing, and you'll be converting types like a pro!
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.