需要小数点来保存并显示三个地方

时间:2011-09-30 20:16:26

标签: c# asp.net

我在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类型,我需要保留这个变量..任何想法?

谢谢

2 个答案:

答案 0 :(得分:4)

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

decimal NewYorkTax = Convert.ToDecimal(txtNewYorkTax.Text);

//... code that is doing stuff with the decimal value ...

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

编辑:澄清了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.
}

答案 1 :(得分:1)

我认为你可以这样使用..

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