1

I can't figure out how to do the following :

I want to import some data from a file, including numeric values. The user can personalize separators, which are char. For exemple, a number may look like this : 2 524,2. Here, we have a "thousands" separator () and a "decimal" separator (,).

I try to convert these strings as double.

I know that I may do something like this :

double.Parse(str.Replace(tSep, '\0').Replace(dSep, '.'));

But I'm looking for a potential way of doing it more properly.

Thank you in advance.

MANOJ GOPI
  • 1,279
  • 10
  • 31
Chostakovitch
  • 965
  • 1
  • 9
  • 33
  • 2
    Use `double.Parse()`or `double.TryParse()` you may create a special `CutureInfo` and set your separators there. – DrKoch Jan 28 '15 at 15:52
  • possible duplicate of [Double parse with culture format](http://stackoverflow.com/questions/5109816/double-parse-with-culture-format) – GSerg Jan 28 '15 at 15:52

2 Answers2

4

Try this:

string s = "2 524,2";

CultureInfo ci = new CultureInfo(1);
NumberFormatInfo ni = new NumberFormatInfo();

ni.NumberGroupSeparator = " ";
ni.NumberDecimalSeparator = ",";
ci.NumberFormat = ni;

decimal d = decimal.Parse(s, ci);
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
2
double.Parse(str.Replace(' ', '\0').Replace(',', '.'));

is fine, but you should also set the culture to InvariantCulture

double.Parse(str.Replace(' ', '\0').Replace(',', '.',
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture));

in order to be sure that your code will work on every user culture setting

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
  • 1
    [Don't use global state to manage a local problem](http://blogs.msdn.com/b/oldnewthing/archive/2008/12/11/9193695.aspx) – GSerg Jan 28 '15 at 15:59
  • 1
    I have a preference for the other methode, even if this gives the same, but thank you for your answer. – Chostakovitch Jan 28 '15 at 16:04