c# adding float numbers behave weirdly [duplicate]

与世无争的帅哥 提交于 2019-12-02 10:03:25

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;

}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!