Decimal Point ignored in Convert.ToDouble [closed]

佐手、 提交于 2020-07-31 04:17:49

问题


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();

回答1:


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.




回答2:


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));



回答3:


It could be a globalization issue as some cultures use , instead of . to separate decimal places. Hopefully it will solve your problem.

string userInput = Console.ReadLine();
double inputInDouble = Convert.ToDouble(userInput,System.Globalization.CultureInfo.InvariantCulture);


来源:https://stackoverflow.com/questions/37461888/decimal-point-ignored-in-convert-todouble

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!