DataGridView: DefaultCellStyle working with decimals

Vijay Balkawade picture Vijay Balkawade · Sep 29, 2011 · Viewed 7.4k times · Source


I am using a Datagidview control on winforms. This is getting filled dynamically. I am trying to display 4 decimal format number in the grid. I applied the DefaultCellStyle property as;

dataGridViewCellStyle2.Format = "N4";
dataGridView1.DefaultCellStyle= dataGridViewCellStyle2;


When I enter data as 21.2134 it displays it properly. But when I enter a complete number like 20, it shows me number as 20.0000. I want to get rid of those trailing 0's. Edit:

One more issue just encountered. with this code it accepts data as 21.2100.


Please help me to resolve this issue.
Thanks in advance.
Vijay

Answer

V4Vendetta picture V4Vendetta · Oct 3, 2011

You should try setting the format as

dataGridViewCellStyle2.Format = "0.####";

This will ensure for upto four decimnal points and would be displayed only if values are present

So in your case it should be 21.2134 and just 20. When you want to access the values use FormattedValue which will do the formatting as specified for the entered value.