How to Convert a String to a Number in Rust
Table of Contents
Rust Recipes is a problem-oriented series of articles that assist developers while learning Rust. Every article solves simple, everyday development tasks using the Rust standard library or leveraging popular and proven crates.
Question: How to convert a string to a number in Rust?
Command-line arguments, environment variables, file contents and query strings all reach our programs as text. To calculate with them, we need numbers. Rust handles this with the parse method on str, which works for every numeric type and returns a Result, because not every string is a valid number.
Parse With a Type Annotation
parse is generic over the target type, so we have to tell Rust what we want. Either annotate the variable or use the “turbofish” syntax ::<T>:
let age: u32 = "42".parse().unwrap();
let temperature = "-3.5".parse::<f64>().unwrap();
Both lines do the same thing in different styles. The annotation is usually more readable, and the turbofish is handy when the value is used directly in an expression.
unwrap is fine for quick experiments, but it panics on invalid input. In real code, handle the Result:
match "42a".parse::<i32>() {
Ok(n) => println!("number: {n}"),
Err(e) => println!("error: {e}"),
}
This prints error: invalid digit found in string.
Watch Out for Whitespace and Ranges
Two things trip people up regularly. First, parse doesn’t ignore whitespace. " 42".parse::<i32>() fails, which bites you when reading lines from a file or from stdin, where the input usually ends with a newline. Call trim first:
let n: i32 = " 42 ".trim().parse().unwrap();
Second, the value has to fit into the target type. "300".parse::<u8>() fails because a u8 only goes up to 255, and "-1".parse::<u32>() fails because unsigned types can’t be negative. Pick a type that matches the range of values you expect.
Parse Floats and Localized Input
parse::<f64>() is more permissive than you might expect. Besides regular decimals, it accepts scientific notation like "1e3" and the special values "nan", "inf" and "infinity". If a value has to be a real number, check is_finite after parsing:
fn parse_temperature(input: &str) -> Result<f64, String> {
let value: f64 = input.trim().parse().map_err(|e| format!("`{input}`: {e}"))?;
if !value.is_finite() {
return Err(format!("`{input}` is not a finite number"));
}
Ok(value)
}
parse_temperature("21.5") returns Ok(21.5), while "nan" and "inf" now return an error instead of slipping through.
Users outside the English-speaking world run into the opposite problem: parse only accepts . as the decimal separator. A German user types 1,5 or 1.234,56. The first fails, and the second fails too, but 1.234 parses happily as 1.234 instead of 1234. The standard library has no locale-aware parsing, but when you know which format to expect, normalize the input before parsing:
use std::num::ParseFloatError;
fn parse_localized(input: &str, decimal: char, grouping: char) -> Result<f64, ParseFloatError> {
let normalized: String = input
.trim()
.chars()
.filter(|&c| c != grouping)
.map(|c| if c == decimal { '.' } else { c })
.collect();
normalized.parse()
}
parse_localized("1.234,56", ',', '.') and parse_localized("1 234,56", ',', ' ') both return Ok(1234.56). Take the separators from a known setting, such as the user’s profile or the format of the file you’re importing, and never guess them from the input: with German separators, "1.5" turns into 15.0.
Fall Back to a Default
When invalid input should just mean “use a sensible default”, unwrap_or keeps it short:
let count = "abc".parse::<usize>().unwrap_or(0);
Be careful with this pattern: it hides typos in configuration values. It’s a good fit for optional, non-critical settings, and a bad one for things like port numbers, where a silent fallback can hide a misconfiguration for a long time.
Return Helpful Error Messages
For integers, the error type ParseIntError tells us why parsing failed through its kind method. That lets us turn a generic error into a message that helps the user fix the input:
use std::num::IntErrorKind;
fn parse_port(input: &str) -> Result<u16, String> {
input
.trim()
.parse::<u16>()
.map_err(|e| match e.kind() {
IntErrorKind::Empty => "port is empty".to_string(),
IntErrorKind::InvalidDigit => format!("`{input}` is not a number"),
IntErrorKind::PosOverflow => format!("`{input}` is larger than {}", u16::MAX),
_ => e.to_string(),
})
}
Calling it with "8080", "", "eighty" and "70000" returns:
Ok(8080)
Err("port is empty")
Err("`eighty` is not a number")
Err("`70000` is larger than 65535")
Parse a List of Numbers
To parse several values at once, combine split with map and collect into a Result<Vec<_>, _>. Collecting into a Result stops at the first invalid value and returns its error, so we either get all numbers or a clear failure:
let numbers: Result<Vec<i32>, _> = "1,2,3".split(',').map(str::parse::<i32>).collect();
// Ok([1, 2, 3])
let numbers: Result<Vec<i32>, _> = "1,x,3".split(',').map(str::parse::<i32>).collect();
// Err(ParseIntError { kind: InvalidDigit })
Hex, Binary and Back to a String
parse only understands decimal numbers. For other bases, every integer type provides from_str_radix:
let color = i64::from_str_radix("ff", 16); // Ok(255)
let flags = u8::from_str_radix("1010", 2); // Ok(10)
from_str_radix expects only the digits, so strip prefixes like 0x or 0b first: u8::from_str_radix("0xff", 16) fails with InvalidDigit.
The other direction is even simpler. Every number implements Display, so to_string and format! turn it back into text:
let n = 255;
let text = n.to_string(); // "255"
let hex = format!("{n:x}"); // "ff"
Recap
Use parse with a type annotation or turbofish to convert strings into numbers, and handle the returned Result instead of unwrapping. Trim input before parsing, pick a type that fits the expected range, and use ParseIntError::kind for helpful error messages. Reject NaN and infinity with is_finite, and normalize localized input with known separators before parsing floats. from_str_radix covers hex and binary, and to_string or format! convert numbers back into strings.