When i want to read a floating point number (like 1.5
) the console gives me an error, but when i try 1,5
it works. How can I switch it so it works with '.'?
This is my code:
double a = double.Parse(Console.ReadLine());
When i want to read a floating point number (like 1.5
) the console gives me an error, but when i try 1,5
it works. How can I switch it so it works with '.'?
This is my code:
double a = double.Parse(Console.ReadLine());
First, it's worth understanding that this has nothing to do with reading it from the console. Console.ReadLine()
is just returning you a string - you'd get the same result if you hard-coded "1.5" as the value to parse.
The problem is that your machine's default culture uses ,
as the decimal separator rather than .
, and double.Parse
is using that default culture to parse the input.
You could either change the current culture as Sebastian says, or for a less invasive approach, you could pass the culture you want to use for parsing (typically the invariant culture in my experience, if you're not trying to use a specific user's culture) into the double.Parse
method directly:
double a = double.Parse(Console.ReadLine(), CultureInfo.InvariantCulture);
I'd personally shy away from changing the global culture unless you really, really want it to affect everything. Aside from anything else, if you specify the invariant culture everywhere you want to use it, it makes it very clear to everyone reading the code that you do want to use the invariant culture.
As an aside, if you want to keep the exact value the user entered, you may well want to use decimal
instead of double
.
I guess your CurrentCulture
does not support .
.
You can try to change it to a culture that supports it, like en-us
.
CultureInfo ci = new CultureInfo("en-us");
Thread.CurrentThread.CurrentCulture = ci;
I suggest extracting a method where you can hide the right format selection (you want .
as a decimal separator and that;s why I suggest using CultureInfo.InvariantCulture
) and syntax check (what if use put bla-bla-bla
?):
using System.Globalization;
...
public static double ReadDouble(string title = null) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
while (true) {
// If syntax correct - i.e. "1.5" return parsed value: 1.5
// If not keep on asking
if (double.TryParse(Console.ReadLine(),
NumberStyles.Any, // accept any style
CultureInfo.InvariantCulture, // invariant culture with . decimal
out var result)) // out var - C# 7.0 syntax
return result;
Console.WriteLine("Sorry, incorrect syntax, repeat the input");
}
}
And then you put
double a = ReadDouble("Please, provide 'a'");
...
double b = ReadDouble("And now, please, provide 'b'");
double c = ReadDouble(); // Just read with no title