我正在使用 C# 和 SQL 2005。
我已将值 0.2 的 float 变量存储到 real 类型的表列中。
当我打开表格检查值时,我发现值为0.200000029...这是已知问题,实数是近似类型。
但是,我已使用 Management Studio 将值更改为 0.2 并重新加载表。数据库现在显示值为 0.2。
问题出在 C# 和 SQL 之间。是否可以像 SQL Management Studio 一样存储 C# 中的值?我想是的,但不知道如何。
有人可以帮忙吗?
多谢。
托马斯
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.
When I opened the table to check the values, I found a value of 0.200000029... It is known problem, real is approximate type.
However, I've changed the value using management studio to 0.2 and reloaded the table. The database is now showing value of 0.2.
The problem lies somewhere between C# and SQL. Is it possible to store values from C# as from SQL management studio? I suppose it is, but don't know how.
Can anyone help?
Thanks a lot.
Tomas
发布评论
评论(2)
如果您存储 0.2 并且只想返回 0.2,请使用
decimal
数据类型。 SQL Server 中的float
值是真正的 IEEEfloat
值,这意味着您可能会在字段中得到 NaN 值。对这些值做任何事情都会导致你的语句崩溃。除非您知道确实需要float
值,否则最好使用decimal
。为了直接回答您的问题,您看到的 .200000....029 只是浮点值的本质。
If you store .2 and want to get back ONLY .2, use the
decimal
data type.float
values in SQL Server are real IEEEfloat
values, which means you can wind up with NaN values in the fields. Doing ANYTHING with those values will cause your statement to crash. Unless you KNOW you really need afloat
value, you're far better off usingdecimal
.To directly answer your question, the .200000....029 you're seeing is just the nature of floating point values.
正如所指出的,您所看到的是浮点数如何以二进制存储的副作用。
对于 0.2f,确切的表示形式是 0.20000000298023223876953125
请参阅 Jon Skeet 的文章以获取有关如何派生的更多信息和代码:
http://www.yoda.arachsys.com/csharp/floatingpoint.html
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
See Jon Skeet's article for more information and code for how that was derived:
http://www.yoda.arachsys.com/csharp/floatingpoint.html