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();
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With