有困难将字符串转换为十进制转换为、字符串、困难、十进制

2023-09-06 21:58:03 作者:姑娘我天生傲骨怎能服输

感谢您抽出宝贵时间来帮助我与我的问题。

Thanks for taking the time to assist me with my problem.

在code我写,我是通过一个表迭代,我得到了适当的值(证实,使用调试器),我解析到相应的类型前,最后我将它们添加一个对象被序列化到XML。

In the code I'm writing, I'm iterating through a table, I get the appropriate values (confirmed it using the debugger) and I'm parsing them to the appropriate types before and finally I add them to an Object to be serialized into XML.

不过,我碰到了一个问题,那就是我似乎无法找到一个方法来解析字符串转换为十进制值。请看下图:

However, I bumped into a problem and that is I can't seem to find a way to parse the string into a decimal value. Take a look:

if (DateTime.TryParse(dateString, culture, styles, out date))
{
   decimal LastValue;
   string vrednost = String.Format("{0:0,0.0}", 
                       row.SelectSingleNode("td[2]").InnerText);

   if (Decimal.TryParse(vrednost, out LastValue))
      list.Add(new StockEntry
                  {
                     Date = date,
                     PoslednaCena = LastValue
                     ...
                  }

需要注意的是vrednost的值是4.451,00,我怀疑,如果我把它转换为4,451.00它会被解析。

Note that the value of vrednost is 4.451,00 and I suspect that if I convert it to 4,451.00 it will get parsed.

我已经成功地解析日期到相应的日期时间值。然而,LastValue的值始终为0我已经用尽了所有我所知道的资源。你有任何想法如何解决我的问题?

I've succeeded in parsing date into the appropriate datetime value. However, the value of LastValue is always 0. I've exhausted all the resources that I know of. Do you have any idea how to solve my problem?

感谢你在前进!

推荐答案

此格式不会做任何事情,因为你不能格式字符串像这样。你必须用解析方法与其他参数,并指定你自己的格式

This formatting will do nothing because you can't format strings like this. You have to use parse method with additional parameters and specify your own format

string s2 = "4.451,00";    
NumberFormatInfo numberFormatInfo = new NumberFormatInfo();
numberFormatInfo.NumberDecimalSeparator = ",";
numberFormatInfo.NumberGroupSeparator = ".";
var d = decimal.Parse(s2, numberFormatInfo);