How to program language independent double.tryparse?

i got string values ​​representing double numbers. (i.e. "1.23"). Always with "."

If you run the code:

double dDouble =0;
string sDemo ="1.23";
double.TryParse(sDemo,out dDouble));

      

it will return 1.23 in dDouble var.

If I switch to another word with "," like "." .... I get 123.0 as dDouble.

How can I guarantee it will always be 1.23 ...

double dDouble =0;
string sDemo ="1.23";
double.TryParse(sDemo,System.Globalization.NumberStyles.Any, 
       System.Globalization.CultureInfo.InvariantCulture, out dDouble));

      

but I'm not sure if this will fix the problem permanently.

I just tried

+3


source to share


1 answer


10 years ago I would have solved it like this (don't do it):

sDemo = sDemo.Replace(",",".");

      

Now



// to string
var text = someDouble.ToString(NumberFormatInfo.InvariantInfo);
// and back
var number = double.Parse(text, NumberFormatInfo.InvariantInfo);

      

The key is to use the same culture. If you are converting values ​​for internal use (for example, passing the value double

as part of the text) - use invariant culture. If, however, you want to display it to the user and then read the user input, then use the same culture anyway: if you don't specify the culture for ToString

, then don't specify it for Parse

, and if you did, then do it again.

+1


source







All Articles