Rui Queirós
Rui Queirós

Reputation: 125

Conversion of String to Double is not right

I am trying to parse doubles infering from a string with the following code:

double.TryParse(contractResult.Result.ValueWithDiscount, NumberStyles.Any, CultureInfo.InvariantCulture, out ValueWithDiscount);
double.TryParse(contractResult.Result.DebitValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value);

But for some reason it is not working. I have two servers that have different configurations from each other. And one is Parsing a "0.5" to 0.5 but the other is parsing to 5.

I also tried to use:

double.TryParse(contractResult.Result.DebitValue, NumberStyles.Any, CultureInfo.CurrentCulture, out Value);

But then the server that was parsing correctly started to parse to 50 instead of 0.5. Any tip of why it is happening?

Update - Values using the following code:

NumberFormatInfo loNumberFormatInfo = new NumberFormatInfo();
loNumberFormatInfo.NumberDecimalSeparator = ".";
loNumberFormatInfo.NumberGroupSeparator = ",";
double ValueWithDiscount = 0.0;
double.TryParse(contractResult.Result.ValueWithDiscount, NumberStyles.Any, loNumberFormatInfo, out ValueWithDiscount);    
logger.Log("ValueWithDiscount: " + contractResult.Result.ValueWithDiscount);
logger.Log("ValueWithDiscount Parsed: " + ValueWithDiscount);

Server that works:

ValueWithDiscount: 0.50
ValueWithDiscount Parsed: 0,5

Server that does not work:

ValueWithDiscount: 0,5
ValueWithDiscount Parsed: 5

Upvotes: 1

Views: 422

Answers (1)

PinBack
PinBack

Reputation: 2564

If you always use a "." as decimal separator you can use a fix FormatInfo to convert.

NumberFormatInfo loNumberFormatInfo = new NumberFormatInfo();
loNumberFormatInfo.NumberDecimalSeparator = ".";
loNumberFormatInfo.NumberGroupSeparator = ",";

double ldOut;
double.TryParse("0.5", NumberStyles.Any, loNumberFormatInfo, out ldOut);

Update:

If your string contains "." and "," you can replace "," before convert.

string lsNumber = "0,5";
lsNumber = lsNumber.Replace(",", ".");

Upvotes: 2

Related Questions