问题
I am trying to add a row's cells and display the total in a new cell in a grid. I am using gridControl from DevExpress. The grid has 12 columns representing the months in a year and I want to add the months values and display the total in the 13th column.
My problem is that if I have a float value of "111,22", it is added as "111,2188" to the database and displayed without the precision in the 13th cell.
So, I have two problems. First one is "why does it insert it as 111,2188 to database?" and the second one is "why does it display the total".
here is my code... this happens when I add 111,2188 and 200, and I get 211,2188 ....
private void calculate_gv_row_total(int row_index) {
float total = 0;
for (int j = 0; start_index + j < start_index + months; j++)
{
float f = float.Parse(gv.GetDataRow(row_index)[start_index + j].ToString());
total = total + f;
}
gv.GetDataRow(row_index)[total_cell_index] = total;
}
how can I solve these problems? What am I doing wrong?
回答1:
Actually, Your Grid is efficient, it rounds off 111,2188 to 111,22. if you want to see the exact value, increase the column width or tell the grid the level of precision.
If you don't need that much precision use ToString("F")
private void calculate_gv_row_total(int row_index) {
float total = 0;
for (int j = 0; start_index + j < start_index + months; j++)
{
float f = float.Parse(gv.GetDataRow(row_index)[start_index + j].ToString("F"));
total = total + f;
}
gv.GetDataRow(row_index)[total_cell_index] = total;
}
回答2:
As Jon Skeet says in a comment, the problem is - to put it bluntly - your understanding of floats. A float uses just 32 bits to store a binary floating point value which must be converted to decimal values. This results in "weird" values like you are experiencing.
The simplest fix is often to just use doubles. But please do read up on floats and why they don't represent base 10 numbers too well.
来源:https://stackoverflow.com/questions/19201295/c-sharp-adding-float-numbers-behave-weirdly