[英]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
. 一种是将"0.5"
解析为0.5
而另一种是解析为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
. 但是随后正确解析的服务器开始解析为50
而不是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
If you always use a "." 如果您始终使用“。” as decimal separator you can use a fix FormatInfo to convert. 作为小数点分隔符,您可以使用固定的FormatInfo进行转换。
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(",", ".");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.