0

I have the following case, from the client side I am getting a double value in a string, this can either be in 'en-GB' format or 'de' format, i.e 123.10 or 123,10. However I need to convert both these number to 123.10. i.e I tried writing the following test using NumberFormatInfo, however it does not pass:

var format = new NumberFormatInfo { NumberGroupSeparator = ",", NumberDecimalSeparator = "." };

        var a = Double.Parse("23000.10", format);
        var b = Double.Parse("23000,10", format);

        Assert.AreEqual(a,b);

What am I doing wrong?

user1950055
  • 157
  • 1
  • 10
  • You merely confirmed that the strings produce different values in en-GB. You already knew that, not much point in testing it. Change to Assert.AreNotEqual() to get the test to pass. – Hans Passant Jan 21 '15 at 19:08
  • right... how do i make them produce the same value without manually checking for a comma and replacing it with a decimal.? – user1950055 Jan 21 '15 at 19:09
  • `Random.Next` would be more readable way to produce random results from user input. `23.000,44` should give you some interesting results... There is really no way to do what you want without knowing the input format (Culture in .Net terms). – Alexei Levenkov Jan 21 '15 at 19:11
  • I added an answer that fix your situation, is not the best way to do, but always change the , for . in your string. Hope it helps. – Christian Amado Jan 21 '15 at 19:50

3 Answers3

1

Well, there is an issue with this kind of conversion.

Anyway, in some project I used the following code:

double a = 0;
double b = 0;

double.TryParse("23000.10".Replace(",","."), out a);
double.TryParse("23000,10".Replace(",", "."), out b);

Assert.AreEqual(a,b);

Isn't the best way to do but it works.

Christian Amado
  • 946
  • 1
  • 7
  • 31
1

how do i make them produce the same value

You can't without knowing the context - if you don't know the context of the input there's no way to distinguish if 123,456 means 123456 or 123.456.

If your input never contains thousands separators (which seems to be the case from your example), then replacing commas with periods is a reasonable solution.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
1

You need to specify culture info, try with this:

var cultureInfo1 = new CultureInfo("de-DE");
var cultureInfo2 = new CultureInfo("en-GB");

var a = Double.Parse("1200,00", cultureInfo1);
var b = Double.Parse("1200.00", cultureInfo2);

Assert.AreEqual(a,b);