DataGridView不正确地渲染浮点数? [英] DataGridView renders float number improperly?

查看:104
本文介绍了DataGridView不正确地渲染浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的SQL服务器表中有一个浮点数列,在将数据插入该表之前,我使用cast()和round()来截断距离小数点太远的任何数字,例如7.6899999999999995应该是舍入并转换为浮点类型为7.69,这些函数的组合完美地工作,当我通过SQL Management Studio中的查询查看该表中的所有行时,float类型列中的所有值都可以,但是当我加载时使用datagridview将表转换为数据集并显示数据,有些值变为原始,就像它们从未被舍入过一样,我的数据库中的值7.69在我的datagridview中变为7.6899999999999995,这太丑了而不是什么我想要。



你能否告诉我任何理由,并建议我解决一下?我完全坚持了这个。



我的帮助将非常感谢!

谢谢!

解决方案

您不想出现的拖尾数字是浮点数的正常行为(特别是单精度数字,如浮点或单),因为它们的内在舍入导致它们以近似的形式存储值。

为了避免这种笨拙的表示,需要明确的舍入。



为了实现这一点,如果你您正在使用DataGridViewTextBoxColumn然后您必须替换 DefaultCellStyle 属性或其格式子属性;



例如:

 Column1.DefaultCellStyle.Format =   N2 ;  //  点后两位数字 





您可以直接从代码或通过网格设计师更改格式。



问候,

Daniele。


I have a column of float number in my SQL server table, before inserting data into that table, I use cast() and round() to truncate any digits which are too far from the decimal point, for example 7.6899999999999995 should be rounded and casted to float type as 7.69, the combination of these functions work perfectly and when I view all the rows from that table by query in SQL Management studio, all the values in the column of float type are OK, but when I load that table into a dataset and display data using a datagridview, there are some values becoming ''original'' like as they had never been rounded, the value 7.69 in my database becomes 7.6899999999999995 in my datagridview, that''s so ugly and not what I want.

Could you please give me any reason for this and suggest me with some solution? I''m stuck at this totally.

Your help would be highly appreciated!
Thanks!

解决方案

The trailing digits You don''t want to appear are normal behavior with floating point numbers (specifically with single precision ones like "float" or "Single") due to their intrinsic rounding that lead them to store the value in an approximated form.
To avoid that akward representation, explicit rounding is needed.

To accomplish that, if You are using a DataGridViewTextBoxColumn then You have to replace DefaultCellStyle property or its Format sub-property;

For example:

Column1.DefaultCellStyle.Format = "N2"; // number with two digits after point



You can change format directly from code or through the grid designer.

Regards,
Daniele.


这篇关于DataGridView不正确地渲染浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆