Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a column with number decimal with max and min in DataGridView?

I want to format the decimal places displayed and captured in a DataGridView, I have a minimum number of decimal places and a maximum number of decimal places. For example:

If caught, "120.0" display "120.00"
If caught "120.01" display "120.01"
If caught "120,123" display "120,123"
If caught "120.1234" display "120.1234"
If caught "120.12348" display "120.1235" (round)

In the DataGridView column "txtcDecimal" has the property (from the designer)

txtcDecimal.DefaultCellStyle.Format = "N2";

txtcDecimal.DefaultCellStyle.Format = "0.00##";  // IS ANSWER. I do not work for an event that interfered

the mask "0.00##" work as "n2" only get 2 decimals which does the correct rounding to two decimal places but just do not like what I need (as I show in the example)

How I can do it in a simple manner without consuming many resources?

Thanks harlam357 & Tom Garske

like image 962
ch2o Avatar asked Jun 27 '12 15:06

ch2o


2 Answers

To format between 2 and 4 decimal places you can use a custom format string.

txtcDecimal.DefaultCellStyle.Format = "0.00##"

To go a bit further...

public partial class Form1
{
   public Form1()
   {
      InitializeComponent();

      var list = new List<Data>();
      list.Add(new Data { Prop1 = 1, Prop2 = 1.2 });
      list.Add(new Data { Prop1 = 2, Prop2 = 1.234567 });

      dataGridView1.Columns.Add("Prop1", "Prop1");
      dataGridView1.Columns["Prop1"].DataPropertyName = "Prop1";
      dataGridView1.Columns.Add("Prop2", "Prop2");
      dataGridView1.Columns["Prop2"].DataPropertyName = "Prop2";
      dataGridView1.Columns["Prop2"].DefaultCellStyle.Format = "0.00##";
      dataGridView1.DataSource = list;
   }

   class Data
   {
      public int Prop1 { get; set; }
      public double Prop2 { get; set; }
   }
}
like image 89
harlam357 Avatar answered Oct 18 '22 09:10

harlam357


Create a custom formatter.

public class MyFormatProvider : IFormatProvider, ICustomFormatter  
{  
   public object GetFormat(Type formatType)  
   {  
     if (formatType == typeof(ICustomFormatter))  
        return this;  
     else  
        return null;  
   }  

   public string Format(string format, object arg, IFormatProvider formatProvider)  
   {  
     // Check whether this is an appropriate callback               
     if (!this.Equals(formatProvider))  
        return null;  

     //if argument/ value is null we return empty string  
     if (arg == null)  
        return null;  

     string resultString = arg.ToString();  

     //transform resultString any way you want (could do operations based on given format parameter)  

     //return the resultant string  
     return resultString;  
   }  
}  

SOURCE: How to custom format data in datagridview during databinding

like image 29
Tom Avatar answered Oct 18 '22 11:10

Tom