【问题标题】:C# passing decimal value to SQL ServerC# 将十进制值传递给 SQL Server
【发布时间】:2017-03-08 08:03:46
【问题描述】:

我正在使用 SQL Server 数据库。表列小数(13,2)我从c#十进制类型参数发送值。我的问题是从c#发送值400.00但值保存40000.00。你能帮我吗?

 decimal amount = Convert.ToDecimal(txttutar.Text,CultureInfo.InvariantCulture)

 SqlCmd.Parameters.Add("@AMOUNT", SqlDbType.Decimal).Value = amount;

【问题讨论】:

  • 请分享您的 C# 代码
  • 我添加了我的 c# 代码
  • amount=? 是什么意思?
  • 您正在使用 InvariantCulture 将您的文本转换为十进制。你确定吗?您的文本框是否包含带有点作为小数分隔符的文本?

标签: c# sql-server decimal


【解决方案1】:

您描述的症状明确表明您的输入与 InvariantCulture 设置不匹配。

如果您的文化使用逗号或除点以外的其他内容作为十进制值的分隔符,则使用 InvariantCulture 转换文本可能会产生错误的值。

例如,在我的文化 (it-IT) 中,使用 InvariantCulture 转换 400,00(it-IT 中的正确小数)会导致提到的值 40000 .
改用 CultureInfo.CurrentCulture

decimal amount = Convert.ToDecimal(txttutar.Text,CultureInfo.CurrentCulture)

也就是说,不要使用 Convert.ToDecimal 来转换用户输入。
如果用户键入的内容不是有效的十进制数(将输入留空或键入“ABC”之类的字符串),则 Convert.ToDecimal 将引发异常。
而是使用 decimal.TryParse 并检查输出

decimal amount;
if(!decimal.TryParse(txttutar.Text, NumberStyles.None, CultureInfo.CurrentCulture, out amount))
    // Message for your user -- Invalid number --
else
    // go on with the database code....

【讨论】:

    【解决方案2】:

    这应该会有所帮助。

    decimal amount = Convert.ToDecimal(txttutar.Text,CultureInfo.InvariantCulture)
    
    SqlParameter amtParam = new SqlParameter("@AMOUNT", SqlDbType.Decimal);
    
    amtParam.Precision = 13;
    amtParam.Scale = 2;
    amtParam.Value = amount;
    
    SqlCmd.Parameters.Add(amtParam);
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 2016-11-01
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多