Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal Point ignored in Convert.ToDouble [closed]

In C# visual studio not taking decimal points in double after read and converted into double using

Convert.ToDouble(Console.ReadLine()); 

command... For example if 12.25 is typed it saves the value as 1225. Can I get any help? This is the Code i'm using.

double number;
Console.WriteLine("Enter a number with a two decimal places!");
number = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(number):
Console.ReadLine();
like image 841
Moorish Awan Avatar asked May 26 '16 13:05

Moorish Awan


2 Answers

Your current code should be working as expected and if it isn't, it's likely the result of cultural issues that expect your double string to be in a different format (i.e. 12,25 instead of 12.25).

Applying the Current Culture When Parsing

You can handle this issue by applying the current culture when parsing your value within the Convert.ToDouble() method through the System.Globalization namespace:

// This would use the current culture to handle reading your value
double input = Convert.ToDouble(Console.ReadLine(),CultureInfo.InvariantCulture);

Handling Various Cultures (i.e. periods or commas)

If you wanted to expect to handle either periods or commas, you could potentially perform a replacement the in the same manner :

// Get the number separator for this culture and replace any others with it
var separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
// Replace any periods or commas with the current culture separator and parse
var input = Double.Parse(Regex.Replace(Console.ReadLine(),"[.,]",separator));

You can see a working example of this here.

like image 81
Rion Williams Avatar answered Nov 16 '22 13:11

Rion Williams


When you local culture doesn't use . as a decimal delimiter it won't work. If you want to enter doubles with a . decimal separator, you need to specify a culture that does use it.

Convert.ToDouble(yourString, System.Globalization.CultureInfo.InvariantCulture)

If you want to output it in the same format, use the same CultureInfo again:

CultureInfo culture = CultureInfo.InvariantCulture;
double input = Convert.ToDouble(Console.ReadLine(), culture);
Console.WriteLine(String.Format(culture, "{0}", input));
like image 6
Manfred Radlwimmer Avatar answered Nov 16 '22 12:11

Manfred Radlwimmer