-1

I made a Regex which filters for double values.

For example one TextBox contains volume and I use this regex for

double ConvertToDouble(String input)
{
    // Matches the first numebr with or without leading minus.
    Match match = Regex.Match(input, "[+-]?\\d*\\.?\\d+");

    if (match.Success)
    { 
        return Double.Parse(match.Value);
    }
    return 0; // Or any other default value.
}

Somehow this returns 0 when I enter 0,5 into the TextBox.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215

2 Answers2

6

I suggest using double.TryParse and get rid of regex at all:

// static : we don't use "this" in the method
static double ConvertToDouble(String input)
{
    // if we can parse input...
    if (double.TryParse(input, out double result))
        return result; // ...return the result of the parsing
    else
        return 0.0;    // otherwise 0.0 or any default value
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • but if for example my TextBox is empty and i try to double.tryparse does it not Crash?? Double.parse crashes for sure is there a difference ? – Explorer2501 Oct 01 '19 at 08:07
  • 1
    @Explorer2501 The Try in TryParse means that it won't throw an exception on empty or invalid input. That's the difference between Parse and TryParse. – ckuri Oct 01 '19 at 08:08
  • @Explorer2501: If `input` is empty, then `double.TryParse` fail to parse it and return `false` and we on turn return `0.0` – Dmitry Bychenko Oct 01 '19 at 08:09
0

Your regex is currently only matching against decimals specified with dot (.) and not a comma (,).

You could modify the regex to accept either using:

[+-]?\d*[\,\.]?\d+

In your code:

Match match = Regex.Match(input, @"[+-]?\d*[\.\,]?\d+");

This would match both 0,5 and 0.5.

Martin
  • 16,093
  • 1
  • 29
  • 48