income = 3.57 (stored in database exactly)
income = 3.6 (programmer want to show the user)
The decimal data type can store maximum of 38 digits. It stores exact representation of the number, there is no approximation of the stored value. Decimal data type can be used to store numbers with decimals when the values must store exactly as specified. We can read more about decimal values from http://msdn.microsoft.com/en-us/library/ms187912(v=sql.105).aspx
In above case programmer want to round off that value at run time binding. As we know about datagridview binding in which data will be shown as same as they are stored in our database. When we bind our list to datagridview it means we are binding each cell one by one. If we want to check which cell is binding to what value then we can do this in Cell Formatting event of datagridview.
Datagridview cell formatting event occurs when the contents of a cell need to be formatted for display. If the standard formatting is insufficient, we can customize the formatting by handling this event. This event occurs every time each cell is painted. Go through datagridview cell formatting event if you want to know more about cell formatting event.
Your cell formatting event should look like the below code if you want to round off all the decimal values bind to this datagridview.
private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
double decValue;
if (e.Value == null)
return;
if (double.TryParse(e.Value.ToString(), out decValue) == false)
return;
e.Value = Math.Round(decValue);
}
{
double decValue;
if (e.Value == null)
return;
if (double.TryParse(e.Value.ToString(), out decValue) == false)
return;
e.Value = Math.Round(decValue);
}
This code will work only with decimal values. It will do nothing if either “value is null” or “value is not type of decimal”. If the value is of type decimal it will round off that value using Math.Round() method. This method rounds a value to its nearest integral value.
Tidak ada komentar:
Posting Komentar