Text to Number Conversion in Programming: A Comprehensive Guide
Data rarely arrives in the exact format we want it. Whether you are scraping a website, importing data from spreadsheets like Excel, or taking input from a user on a web form, numerical data almost always starts its life in a program as text—a string of characters.
Before you can perform any mathematical operations on that data, you must translate it from a text string into a native numerical data type (like an integer or a float). Under the hood, text is stored using character encoding standards where each symbol corresponds to a numeric code point, such as standard ASCII. If you try to add the string "5" to the string "10", you will not get 15; you will get "510".
This process, known as parsing or type casting, is a foundational skill in software development. In this guide, we will explore how to convert text to numbers in some of the world’s most popular programming languages: Python, JavaScript, and Java. We will also discuss common edge cases and errors you will encounter along the way.
(Note: If you are an end-user looking to simply convert spelled-out English words like “two thousand” into digits or numbers into words, you can use our free online converter!)
Python: Simple and Straightforward
Python is renowned for its readability, and type conversion is no exception. Python provides built-in functions that make text-to-number conversion seamless.
Using int() and float()
If you have a string that contains whole digits, you use the int() function. If the string contains a decimal, you use the float() function.
# Converting to an integer
age_string = "25"
age_number = int(age_string)
print(age_number + 5) # Outputs: 30
# Converting to a float
price_string = "19.99"
price_number = float(price_string)
print(price_number * 2) # Outputs: 39.98
Common Pitfall: If you try to pass a string containing a decimal into int(), Python will throw a ValueError.
# This will crash!
value = int("10.5")
To fix this, either parse it as a float first, or ensure your string is a clean whole number.
Converting English Words to Numbers
What if you have the string "twenty five" instead of "25"? Python’s standard library doesn’t parse English words natively. For this, developers rely on external libraries, the most popular being word2number.
# pip install word2number
from word2number import w2n
text_number = "two million three thousand nineteen"
integer_value = w2n.word_to_num(text_number)
print(integer_value) # Outputs: 2003019
JavaScript: The Wild West of Type Coercion
JavaScript’s approach to converting strings to numbers is notoriously flexible—and sometimes confusing due to its dynamic typing and automatic type coercion.
Using parseInt() and parseFloat()
The standard way to extract numbers from strings in JavaScript is using the parseInt() and parseFloat() functions.
const strInt = "42";
const strFloat = "3.14159";
console.log(parseInt(strInt)); // Outputs: 42
console.log(parseFloat(strFloat)); // Outputs: 3.14159
A handy feature of parseInt is that it will try to extract a number even if there is text attached to the end of it, reading left-to-right until it hits a non-numeric character.
console.log(parseInt("100px")); // Outputs: 100
console.log(parseInt("Weight: 100")); // Outputs: NaN (Not a Number)
Crucial Advice for parseInt: Always provide the radix (the base of the mathematical numeral system) as the second argument to avoid unpredictable behavior in older browsers.
parseInt("08", 10); // The 10 explicitly tells JS to use Base-10.
The Unary Plus and Number()
JavaScript developers frequently use shorthand tricks to convert strings to numbers. The Number() constructor and the unary plus + operator are common.
const val = "500";
console.log(Number(val)); // Outputs: 500
console.log(+val); // Outputs: 500
Unlike parseInt, these strict methods will result in NaN if there are any alphabetical characters in the string (e.g., +"100px" results in NaN).
Java: Strictly Typed Parsing
Java is a statically typed language. You must be very explicit about what types of data you are creating and manipulating. Java utilizes wrapper classes like Integer and Double to parse text.
Using Integer.parseInt()
To convert a string to a primitive int, you use the parseInt method from the Integer class.
public class Main {
public static void main(String[] args) {
String numberStr = "1024";
int number = Integer.parseInt(numberStr);
System.out.println(number / 2); // Outputs: 512
}
}
Similarly, for floating-point numbers, you use Double.parseDouble().
String piStr = "3.14";
double pi = Double.parseDouble(piStr);
Handling Errors: In Java, if the string is completely malformed (e.g., "five", "10a", or null), parseInt will throw a NumberFormatException at runtime. Robust Java applications always wrap parsing logic in a try-catch block.
String badData = "100 apples";
try {
int count = Integer.parseInt(badData);
} catch (NumberFormatException e) {
System.out.println("Invalid numeric string provided!");
}
Common Edge Cases Across All Languages
No matter which language you use, text-to-number conversion has universal landmines you must watch out for:
- Whitespace: Leading and trailing whitespace (
" 45 ") is usually handled gracefully by modern parsers, but internal whitespace ("4 5") will often cause errors or result inNaN. Always.trim()your strings if you suspect messy input. - Thousands Separators: Commas in numbers (
"1,000") will break standard parsers in Python, Java, and JS. The parser sees the comma as an alphabetical character. You typically have to remove commas using string replacement before parsing. - Empty Strings: What happens when you try to parse an empty string
""? In Python and Java, this throws an error. In JavaScript,Number("")surprisingly returns0, which can introduce hidden logic bugs. - Localization: In many European countries, a comma is used as a decimal separator (e.g.,
3,14), while a period is used for thousands (1.000,50). Native parsers usually default to US locale. If your app serves an international audience, you must use locale-aware parsing libraries.
Conclusion
Converting text to numbers is a task every programmer executes daily. While the syntax differs—int() in Python, parseInt() in JS, Integer.parseInt() in Java—the core concepts remain identical. By understanding how your chosen language handles invalid characters, decimals, and edge cases, you can write robust code that processes user input safely and accurately.
And if you’re building a tool that needs to interpret spelled-out text (like “one hundred and five”) into digits without writing complex regex and logic yourself, you can take inspiration from the algorithms powering the Word to Number Converter!