C# 到 SQL 浮点值转换

发布于 2024-08-19 16:52:32 字数 329 浏览 1 评论 0 原文

我正在使用 C# 和 SQL 2005。 我已将值 0.2float 变量存储到 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小猫一只 2024-08-26 16:52:32

如果您存储 0.2 并且只想返回 0.2,请使用 decimal 数据类型。 SQL Server 中的 float 值是真正的 IEEE float 值,这意味着您可能会在字段中得到 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 IEEE float 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 a float value, you're far better off using decimal.

To directly answer your question, the .200000....029 you're seeing is just the nature of floating point values.

梦过后 2024-08-26 16:52:32

正如所指出的,您所看到的是浮点数如何以二进制存储的副作用。

对于 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文