Search code examples
c#parsinginternationalizationdoublecultureinfo

Parsing double with dot to comma


I am working with doubles. In the Netherlands we make use of 51,3 instead of 51.3. I did write a piece of code that works with dots instead of commas. But the result of the previously written code returns a double the English way, with a dot. I am encountering some strange errors.

Here is what I have:

var calResult = 15.2d;
var calResultString = calResult.ToString(CultureInfo.GetCultureInfo("nl-NL"));
var result = double.Parse(calResultString);
  1. calResult == "15.2" -> as expected
  2. calResultString == "15,2" -> as expected
  3. result == "152" -> here I expect a comma.

A also did try to add the cultureinfo also in the double.Parse. This resulted in a "15.2".

TLDR: I need to convert an English/American double to a Dutch(or similar rules) one.

Thanks in advance! :)

P.S

I hope this is not a duplicate question, but didn't found anything this specific.


Solution

  • You, probably, should either provide "nl-NL" whenever you work with Netherlands' culture

      var calResult = 15.2d;
      var calResultString = calResult.ToString(CultureInfo.GetCultureInfo("nl-NL"));
      // We should parse with "nl-NL", not with CurrentCulture which seems to be "en-US"
      var result = double.Parse(calResultString, CultureInfo.GetCultureInfo("nl-NL")); 
    

    Or specify CurrentCulture (default culture)

      CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("nl-NL");
    
      var calResult = 15.2d;
      // now CultureInfo.GetCultureInfo("nl-NL") is redundant 
      var calResultString = calResult.ToString(); 
      var result = double.Parse(calResultString); 
    

    Finally, if you have a string which represents some floating point value in en-US culture, and you want the same value but be a string in nl-NL format:

      string source = "123.456";
    
      string result = double
        .Parse(source, CultureInfo.GetCultureInfo("en-US"))
        .ToString(CultureInfo.GetCultureInfo("nl-NL"));