I have found many questions for this topic but I couldn't find one that covers my case.
For a string input, which may be or may not be a real number of unknown culture, how can I try to cast it to a double with CultureInfo.InvariantCulture?
Can this be solved for the special case that the decimal separator may be '.' or ',' by some clever algorithm comparing the parsed values?
private double? tryGetDouble(string input) {
if (double.TryParse(input, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out double result)) {
// This will work for "1.25", but "1,25" will be converted to 125.
return result;
}
return null;
}
I was thinking something along the lines of, parse the string with both a '.' and a ',' culture and reach a verdict based on the comparison of the parsed number in both cases.
The culture information cannot, and should not be ignored. It would be impossible to even write a custom formatter to do this. How would it know the difference between "1.000" being 1000 or 1?
My best advice would be to pass the culture code for the value you sent along with the input. Somewhere along the way, someone is running in a particular culture code. From there you should be able to load the appropriate culture and parse the number correctly.