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.
}
Run Code Online (Sandbox Code Playgroud)
Somehow this returns 0 when I enter 0,5 into the TextBox.
我建议使用double.TryParse并完全摆脱正则表达式:
// 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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48 次 |
| 最近记录: |