Nick
Nick

Reputation: 3

C# read decimal number from keyboard

Hi I have just started learning C# and I have written a simple program which is supposed to read values entered from the keyboard. The code I use to do that is:

    try {
    x=double.Parse(Console.ReadLine(),CultureInfo.InvariantCulture.NumberFormat);
        }
    catch (System.FormatException)
    {//error message }        

The problem is that if I enter 1,2 the value stored in x is 12. Is there any way I can read this value as 1.2, so converting the comma into a point?

Also if I enter 1,,3 the value would be 13 and no error is generated.

Upvotes: 0

Views: 1842

Answers (2)

Steve
Steve

Reputation: 216293

You should use double.TryParse instead and pass the appropriate culture info.

double x;
CultureInfo ci = new CultureInfo("it-IT"); 
if(double.TryParse(Console.ReadLine(),NumberStyles.AllowDecimalPoint, ci, out x))
    MessageBox.Show("It is a double number");
else
    MessageBox.Show("Not a double");

You could also try with the simple version that doesn't require a CultureInfo and NumberStyles parameters, but, in this case, you get the conversion based on the current culture of your machine and this could be agreeable or not depending on your intentions.

if(double.TryParse(Console.ReadLine(),out x))
    .....

Using Culture.InvariantCulture means that the parsing is executed using the default operating system culture that it is associated with the English language but not with any country/region.

An important benefit of TryParse is that you avoid the code to handle the possible exceptions raised by the simple Parse method. Exceptions should be always avoided as a method to control the flow of your program when you have alternatives. (Performance hit).

Upvotes: 1

Anirudha
Anirudha

Reputation: 32797

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ",";
Double.Parse(num,nfi);

Upvotes: 0

Related Questions