0

I am trying to read a number from the console, but if it is input via comma (ex. 2,56), it cannot be parsed successfully. It can be parsed only if it is input like this: 2.56 How can I change that? Here is a sample code:

       if (double.TryParse(stringElements[i], out doubleNum))
                {
                    averageTime.Add(doubleNum);
                }
Mihayloff
  • 27
  • 5
  • 1
    What is your `CurrentCulture`? Also show your code as well. By the way, I don't like this `.Replace` suggestions. Because if your string has `,` as a thousands separator, your code will be broken as well and your parsing will fail probably (depends on your current culture thread of course). – Soner Gönül May 01 '14 at 10:55
  • 1
    I think @SonerGönül's comment is correct, but as a hack, if you are sure it will be a number, can you not simply replace a single comma with a fullstop and then just parse. – Anthony Horne May 01 '14 at 10:56
  • What language is the user supposed to have? Bulgarian? Use appropriate `CultureInfo`. Don't replace separators with `string.Replace`! – Jeppe Stig Nielsen May 01 '14 at 11:00
  • @Mihayloff: are you wanting to support _only_ commas (that is `2,56` is valid, but `2.56` will fail) or do you want to be able to support _both_ formats simultaneously? – Chris Sinclair May 01 '14 at 11:01
  • @ChrisSinclair yes I would like to support both formats if possible – Mihayloff May 01 '14 at 11:03
  • 1
    @Mihayloff: Then `Replace` is a quick hack fix (Assuming thousands separators are not an issue for you). Off the top of my head, maybe something more permanent would be to _try_ parsing with one Culture (decimals) and if it fails, _then_ try parsing with a different Culture (commas), and if that fails, assume the input is garbage. – Chris Sinclair May 01 '14 at 11:05

2 Answers2

0

replace the comma by '.' like this :

save your number in variable X , then

if (double.TryParse((X).Replace(",", "."), out tmp))
{

}
Alaa Mohammed
  • 382
  • 2
  • 14
0

replace with "."

Convert.ToDouble("2,56".Replace(",", "."));
Raju Padhara
  • 687
  • 1
  • 7
  • 20