How do I programm a language independent double.tryparse?
i got string values representing doubles. (fe "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 to the dDouble var.
If i switch to a different languge with "," as "." .... i get 123.0 as dDouble.
How do I ensure that its always 1.23 ...
double dDouble =0;
string sDemo ="1.23";
double.TryParse(sDemo,System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out dDouble));
but I am unsure, if this will solve the problem permanently.
i just tried
10 years ago I would solve it like this (do not do that):
sDemo = sDemo.Replace(",",".");
Now
// to string
var text = someDouble.ToString(NumberFormatInfo.InvariantInfo);
// and back
var number = double.Parse(text, NumberFormatInfo.InvariantInfo);
Key point is to use same culture. If you convert values for internal use (to example, passing double
value as a part of text) - use invariant culture. If, however, you want to display it to the user and then read user input, then still use same culture: if you don't specify culture for ToString
, then don't specify it for Parse
, and if you did, then do it again.
上一篇: 以特定模式格式化日期字符串