简体   繁体   English

C#到SQL浮点值转换

[英]C# to SQL float values conversion

I'm working with C# and SQL 2005. I've stored a float variable of the value 0.2 into table column of real type. 我正在使用C#和SQL2005。已将值0.2float变量存储到型表列中。 When I opened the table to check the values, I found a value of 0.200000029... It is known problem, real is approximate type. 当我打开表格检查值时,我发现值0.200000029 ...这是已知的问题,实际是近似类型。 However, I've changed the value using management studio to 0.2 and reloaded the table. 但是,我已经使用Management Studio将值更改为0.2,然后重新加载了表格。 The database is now showing value of 0.2. 数据库现在显示值为0.2。

The problem lies somewhere between C# and SQL. 问题出在C#和SQL之间。 Is it possible to store values from C# as from SQL management studio? 是否可以像SQL Management Studio一样存储C#中的值? I suppose it is, but don't know how. 我想是的,但是不知道如何。

Can anyone help? 有人可以帮忙吗? Thanks a lot. 非常感谢。

Tomas 托马斯

If you store .2 and want to get back ONLY .2, use the decimal data type. 如果您存储.2并且只想返回.2,请使用decimal数据类型。 float values in SQL Server are real IEEE float values, which means you can wind up with NaN values in the fields. float在SQL Server中值是实IEEE float值,这意味着你可以风与在田间NaN值。 Doing ANYTHING with those values will cause your statement to crash. 对这些值进行任何操作都会导致语句崩溃。 Unless you KNOW you really need a float value, you're far better off using decimal . 除非您知道您确实需要一个float值,否则使用decimal会更好。

To directly answer your question, the .200000....029 you're seeing is just the nature of floating point values. 要直接回答您的问题,您看到的.200000 .... 029只是浮点值的性质。

As pointed out, what you are seeing is a side effect of how floating point numbers are stored in binary. 如所指出的,您所看到的是浮点数如何以二进制形式存储的副作用。

For 0.2f, the exact representation is 0.20000000298023223876953125 对于0.2f,精确表示为0.20000000298023223876953125

See Jon Skeet's article for more information and code for how that was derived: 有关更多信息和代码,请参阅Jon Skeet的文章:

http://www.yoda.arachsys.com/csharp/floatingpoint.html http://www.yoda.arachsys.com/csharp/floatingpoint.html

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

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