C#
double.Parse
Learn to read floating-point numbers with double.Parse.
Decimals with double.Parse
When you need a decimal number instead of an integer, use the double.Parse method. It converts a string to a double and throws FormatException if it cannot. You will meet it often with prices, temperatures, or lengths.
For example, double d = double.Parse("3.14"); assigns 3.14 to d. An important detail: the decimal separator is culture-dependent. Turkish locale uses a comma, English locale uses a dot. We will look at this in the next card.
Consistency with CultureInfo
Because the decimal separator depends on locale, double.Parse may behave differently on different machines. For consistency you use CultureInfo.InvariantCulture, so the separator is always a dot.
For example, double.Parse("3.14", CultureInfo.InvariantCulture) returns 3.14 regardless of locale. To use this, add using System.Globalization; at the top of the file. This matters for data exchange and file reading.
double.TryParse
Just like int.TryParse, double.TryParse does a safe conversion. Instead of throwing, it returns a bool and passes the result through an out parameter. It is ideal when reading prices or measurements from the user.
For example, if (double.TryParse(input, out double price)) parses the input safely. If it fails, price becomes zero and the if block is skipped. Your program then continues without crashing on invalid input.
Exercise Parse the price safely
Convert input into price using double.TryParse. If parsing succeeds, print price with Console.WriteLine. Use an if on the return value of TryParse.
Show example solution
Declare double price; then check with if (double.TryParse(input, out price)) and print price with WriteLine.
Example solution:
using System;
class Program
{
static void Main()
{
string input = "25";
double price;
if (double.TryParse(input, out price))
{
Console.WriteLine(price);
}
}
}
Test yourself
-
What does double.Parse("3.14") return? (default culture)
double d = double.Parse("3.14");
- 3.14
- 3
- Throws FormatException
- 31.4
Show answer
3.14 — Correct! With a dot, English locales parse the value as 3.14.
-
Parse with Invariant
using System.Globalization;
string s = "3.14";
double d = double____;
Console.WriteLine(d);
Show answer
using System.Globalization;
string s = "3.14";
double d = double.Parse(s, CultureInfo.InvariantCulture);
Console.WriteLine(d);
-
Match the call with its result
- double.Parse("3.14")
- 3.14
- double.TryParse("abc", out _)
- false
- Parse with InvariantCulture
- locale-independent
Next lesson: Console formatting