Reputation: 157
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?
Upvotes: 0
Views: 104
Reputation: 120
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);
Upvotes: 1
Reputation: 152644
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.
Upvotes: 1
Reputation: 943
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.
Upvotes: 1