3

i got string values representing doubles. (f.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 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

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
lost bit
  • 45
  • 5
  • 1
    By different language you mean different culture? – Yuval Itzchakov Nov 21 '14 at 11:12
  • 3
    Using the InvariantCulture *is* the recommended way of writing locale-agnostic conversions of numbers and dates. – Panagiotis Kanavos Nov 21 '14 at 11:14
  • In both the end(`double.TryParse` and `double.ToString`), you need to use same culture. – Sriram Sakthivel Nov 21 '14 at 11:20
  • 1
    Do you know the language/culture/format that was used as the double was written as string? If not then you don't stand a chance to parse it correctly. You could try-parse the whole file(or whatever it is) and look which was more successful. – Tim Schmelter Nov 21 '14 at 11:46
  • To the questions: Original format: English, but's a proprietary software ... no .Net. Language: German / English / Chineese – lost bit Nov 21 '14 at 13:44
  • So I will stay with the InvariantCulture statement. Is this Invariant Culture based on the Englisch one? – lost bit Nov 21 '14 at 13:47
  • @lostbit, ask that question google directly ;) [Click](http://stackoverflow.com/q/9760237/1997232), [click](http://stackoverflow.com/q/2423377/1997232) ... – Sinatr Nov 21 '14 at 13:54

1 Answers1

3

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.

Sinatr
  • 20,892
  • 15
  • 90
  • 319