代码没有转换文本

本文关键字:文本 转换 代码 | 更新日期: 2023-09-27 18:14:01

我有一个文本框,允许用户输入十进制值,然后将其存储在数据库中的表中,这段代码在开发环境中工作。我现在已经将我的项目发布到服务器,现在不再使用带有小数点的值。

decimal ReceiptAmount;
decimal AmountDue;
decimal Change;
if (!string.IsNullOrEmpty(((TextBox)dl_Item.FindControl("tb_ReceiptAmount")).Text))
{
    if (((TextBox)dl_Item.FindControl("tb_ReceiptAmount")).Text.Contains(".") == true)
    {
        ReceiptAmount = Convert.ToDecimal(((TextBox)dl_Item.FindControl("tb_ReceiptAmount")).Text.Replace(".", ","));
    }
    else
    {
        ReceiptAmount = Convert.ToDecimal(((TextBox)dl_Item.FindControl("tb_ReceiptAmount")).Text);
    }
}
else
{
    ReceiptAmount = 0;
}
if (!string.IsNullOrEmpty(((TextBox)dl_Item.FindControl("tb_AmountDue")).Text))
{
    if (((TextBox)dl_Item.FindControl("tb_AmountDue")).Text.Contains(".") == true)
    {
        AmountDue = Convert.ToDecimal(((TextBox)dl_Item.FindControl("tb_AmountDue")).Text.Replace(".", ","));
    }
    else
    {
        AmountDue = Convert.ToDecimal(((TextBox)dl_Item.FindControl("tb_AmountDue")).Text);
    }
}
else
{
    AmountDue = 0;
}
if (!string.IsNullOrEmpty(((TextBox)dl_Item.FindControl("tb_Change")).Text))
{
    if (((TextBox)dl_Item.FindControl("tb_Change")).Text.Contains(".") == true)
    {
        Change = Convert.ToDecimal(((TextBox)dl_Item.FindControl("tb_Change")).Text.Replace(".", ","));
    }
    else
    {
        Change = Convert.ToDecimal(((TextBox)dl_Item.FindControl("tb_Change")).Text);
    }
}
else
{
    Change = 0;
}

我不确定这段代码有什么问题。文本框是在一个数据列表中找到的,我循环遍历该数据列表以获取所有值。

代码没有转换文本

以字符串为输入的Convert.ToDecimal过载将使用CultureInfo.CurrentCulture解析字符串。可能您的服务器有不同的区域设置。根据区域设置,逗号或点可能被解释为千位分隔符(因此被忽略),也可能被解释为小数分隔符。

相反,您应该直接使用Decimal.Parse,根据您的用例提供特定的文化或不变的文化。

理想情况下,你应该把用户的文化设置在某个地方。要实现这一点,有多种方法,例如,对于ASP。Web表单:https://msdn.microsoft.com/en-us/library/bz9tc508.aspx

如果使用正确的区域性解析字符串,则可以摆脱字符串操作,将.替换为,

首先,像

  if (!string.IsNullOrEmpty(((TextBox)dl_Item.FindControl("tb_ReceiptAmount")).Text))

look very ugly;让我们提取一个方法(复制/粘贴是非常非常糟糕的做法):

  private String FindDLText(String controlName) {
    var box = dl_Item.FindControl(controlName) as TextBox;
    return box == null ? null : box.Text;
  }

那么你不需要检查Text.Contains(".") == true,只要检查Replace,如果你真的需要它:

  private Decimal FindDLValue(String controlName) {
    String text = FindDLText(controlName); 
    if (String.IsNullOrEmpty(text))
      return 0.0M;
    //TODO: check if you really need this
    //text = text.Replace(".", ",");
    // you have to specify Culture either InvariantCulture or some predefined one;
    // say, new CultureInfo("ru-RU") // <- use Russian Culture to parse this
    return Decimal.Parse(text, CultureInfo.InvariantCulture);
  }
最后,你可以得到
  decimal ReceiptAmount = FindDLValue("tb_ReceiptAmount");
  decimal AmountDue = FindDLValue("tb_AmountDue");
  decimal Change = FindDLValue("tb_Change"); 

感觉不同:t三个明显的行和两个简单的方法。