c# Windows Forms Application: Convert.ToDecimal 不产生预期的结果



我正在尝试从XML文件中十进制化变量值。 我用来执行此操作的代码是:

//round monitory values to 2 decimal palaces, even if none are given
decimal totalAmount = Math.Round(Convert.ToDecimal(xn.Attributes["totalAmount"].Value), 2);
decimal paid = Math.Round(Convert.ToDecimal(xn.Attributes["paidAmount"].Value), 2);
decimal due = Math.Round(Convert.ToDecimal(xn.Attributes["dueAmount"].Value), 2);

它们在 XML 文件中的值是:

totalAmount="538.0000" 
paidAmount="0.0"
dueAmount="527"

结果是:

totalAmount="538.00"   -  GREAT 
paidAmount="0.0"       -  No Change
dueAmount="527"        -  No Change

我想出去的是

totalAmount="538.00" 
paidAmount="0.00"
dueAmount="527.00"

有人可以指出我哪里出错了吗?

谢谢

您似乎将舍入与格式混淆了。

要获取所需的字符串,您需要执行以下操作:

string totalFormatted = totalAmount.ToString("F");
string paidFormatted = paidAmount.ToString("F");
string dueFormatted = dueAmount.ToString("F");

最新更新