C# Reference ยท Numbers and Math
C# int.Parse() and TryParse()
Reference for C# Parse and TryParse on int, double and decimal: NumberStyles, culture rules, spans and how to handle bad input without exceptions.
Every numeric type in .NET has a static Parse method that turns text into a number, and a matching TryParse that does the same without throwing. Parse throws FormatException for bad text, OverflowException for numbers that do not fit and ArgumentNullException for null. TryParse returns false and sets the out value to zero instead.
For anything a person typed or a file supplied, use TryParse: bad input is expected, not exceptional. The examples use int, but long, double, decimal, byte, BigInteger and the others work the same way.
if (int.TryParse("123", out int n)) { Console.WriteLine(n + 1); // 124 }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static int int.Parse(string s) public static int int.Parse(string s, IFormatProvider? provider) public static int int.Parse(string s, NumberStyles style, IFormatProvider? provider) public static int int.Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) public static int int.Parse(ReadOnlySpan<byte> utf8Text, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) public static bool int.TryParse(string? s, out int result) public static bool int.TryParse(string? s, IFormatProvider? provider, out int result) public static bool int.TryParse(string? s, NumberStyles style, IFormatProvider? provider, out int result) public static bool int.TryParse(ReadOnlySpan<char> s, out int result)
| Name | Description |
|---|---|
s |
The text to parse. A span avoids creating a substring. UTF-8 byte spans (.NET 8+) skip decoding. |
style |
A NumberStyles value controlling accepted syntax: Integer (default for integers), Float, Number, AllowThousands, AllowHexSpecifier/HexNumber, Currency, AllowParentheses and more. |
provider |
A CultureInfo or NumberFormatInfo that defines the decimal separator, group separator and sign symbols. |
result |
(TryParse) receives the parsed number, or 0 when parsing fails. |
Returns: Parse returns the number. TryParse returns true on success.
Errors: Parse throws ArgumentNullException (s is null), FormatException (text is empty or not valid for the style) and OverflowException (value outside the type's range). TryParse never throws for these cases.
Usage notes
- Defaults are strict.
int.Parseallows leading and trailing white space and a leading sign. It rejects thousands separators, decimal points ("12.5"), exponents, and an empty string. - Floating-point defaults are wider.
double.ParseusesNumberStyles.Float | AllowThousands, so it accepts"1,234.5"and"1e3"."NaN","Infinity"and"-Infinity"are accepted by their symbol names. - Specify the culture. The overloads without a provider use the current culture, which affects the decimal separator. For data files, protocols and JSON, pass
CultureInfo.InvariantCulture. This runner is always invariant, so culture-specific output (such asde-DE) cannot be demonstrated here. - Hexadecimal.
NumberStyles.HexNumberaccepts digits without a0xprefix and parses as two's complement, soint.Parse("FFFFFFFF", NumberStyles.HexNumber)is-1. - Failure leaves zero. After a failed
TryParse, the variable holds0(ordefault). Check the return value, not the number. - Cost of exceptions. Throwing is orders of magnitude slower than returning
false. UseTryParsein loops that read untrusted data. - Generic code. Every number type implements
IParsable<T>(andISpanParsable<T>), soT.Parse(s, provider)andT.TryParsework in generic methods. Convert.ToInt32(string)parses too, but returns0fornulland gives no control over styles. Seenum-convert.
Related
num-convertandnum-tostringtype-int,type-float-doubleandtype-decimalstr-culture- Tutorial: Type conversion