需要小数来保存和显示三个位置



我在c#中有这行代码,但是如果它总是将文本框重置为0.00格式,我该如何使它保持0.000格式呢?

NewYorkTax = Convert.ToDecimal(txtNewYorkTax.Text);
 //converts it but with 0.00, I need 0.000 or 7.861 etc..

注:NewYorkTax的类型是Decimal,我需要保留这个变量。什么好主意吗?

谢谢

你需要格式化文本框中的字符串:

decimal NewYorkTax = Convert.ToDecimal(txtNewYorkTax.Text);
//... code that is doing stuff with the decimal value ...
txtNewYorkTax.Text = String.Format("{0:0.000}", NewYorkTax);

EDIT:澄清String.Format的使用

第二次编辑:关于异常

还要记住在接受人工输入时转换为十进制的风险。人类是容易出错的生物。:)

它有助于使用TryParse, Decimal支持:

decimal NewYorkTax;
if (Decimal.TryParse(txtNewYorkTax.Text, out NewYorkTax)) // Returns true on valid input, on top of converting your string to decimal.
{
    // ... code that is doing stuff with the decimal value ...
    txtNewYorkTax.Text = String.Format("{0:0.000}", NewYorkTax);
}
else
{
    // do your error handling here.
}

我想你可以这样用…

NewYorkTax = Convert.ToDecimal(String.Format("{0:0.000}", Convert.ToDecimal(txtNewYorkTax.Text)));

最新更新