简体   繁体   English

如何在c#中转换sql类型的双精度

[英]How to convert sql type double-precision in c#

I have a database access, and one of this field is double-precision. 我有一个数据库访问权限,其中一个字段是双精度的。 Normally if i set in the textbox 1.71 or 1,71 the field in database should contain 1.71. 通常,如果我在文本框1.71或1,71中设置,则数据库中的字段应包含1.71。

But if i execute query the value of acces'field is 171 !!. 但是如果我执行查询,acces'field的值是171 !!

public const string QUERY = 
        @"UPDATE TBLART 
          SET TBLART.COST = @cost
          WHERE TBLART.CODE= '1'";

var param = new DynamicParameters();
var cost = totalCost.Replace(',', '.'); //totalCost is a textbox
param.Add("cost", Double.Parse(cost), DbType.Double);

gsmconn.Execute(QUERY, param);

What i wrong ? 我错了什么? Thanks. 谢谢。

double.Parse will use the current thread's culture by default. double.Parse默认使用当前线程的文化。 I suspect your current culture uses "." 怀疑你现在的文化是用“。” as a grouping separator. 作为分组分隔符。

Two options: 两种选择:

  • Continue to use Replace as you are already doing, but then specify CultureInfo.InvariantCulture when parsing 继续使用您正在执行的Replace ,但在解析时指定CultureInfo.InvariantCulture
  • Remove the replacement, and just use the current thread's culture when parsing the original value. 删除替换,并在解析原始值时使用当前线程的文化。 This relies on the culture being appropriate for the user, but is probably a better solution when that's the case. 这依赖于适合用户的文化,但在这种情况下可能是更好的解决方案。 (Otherwise someone entering "1,234.56" will get a parse error when they expected a value of "just a bit more than 1234".) (否则输入“1,234.56”的人在预期“只是超过1234”的值时会得到一个解析错误。)

If I remember correctly in windows forms you can bind an double property to a textbox and it will automatically take care of parsing and converting. 如果我在Windows窗体中正确记住,您可以将double属性绑定到文本框,它将自动处理解析和转换。 You should not manually do parsing from string to double. 您不应该手动从字符串解析为double。

That problem is already solved fro you by the .NET framework. 这个问题已经由.NET框架解决了。

Another suggestion, your data access code should not do any parsing. 另一个建议是,您的数据访问代码不应该进行任何解析。 That should be done in some higher layer. 这应该在更高层进行。 But better leave it to the framework. 但最好把它留给框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM