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

3

7

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

Adlare answered 27/6, 2012 at 15:18 Comment(2)
In your third example did you specify a comma (,) on purpose to denote a whole number or was that a typo?Martz
Please see that I updated my answer to show how it was implemented in Forms. Glad to see you got it to work!Undersell
M
18

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; }
   }
}
Martz answered 27/6, 2012 at 15:34 Comment(0)
U
3

To format between 2 and 4 decimal places you can use a custom format string. (As provided by Harlam357)

txtcDecimal.DefaultCellStyle.Format = "0.00##"

I verified it with the following simple console application:

        double myDouble = 13.1;
        double myDouble2 = 13.12345;
        Console.WriteLine(myDouble.ToString("0.00##"));
        Console.WriteLine(myDouble2.ToString("0.00##"));
        Console.Read();

The output was:

13.10
13.1235

Harlam's answer is clearly correct....

UPDATE: This is how I implemented it in forms:

    public Form1()
    {
        InitializeComponent();

        DataTable dt = new DataTable();
        dt.Columns.Add("a");
        dt.Rows.Add(123.4);
        dt.Rows.Add(123.45);
        dt.Rows.Add(123.456);
        dt.Rows.Add(123.4567);
        dt.Rows.Add(123.45678);
        this.dataGridView1.DataSource = dt;
        this.dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);
    }

    void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (e.ColumnIndex == 0 && e.RowIndex != this.dataGridView1.NewRowIndex)
        {
            double d = double.Parse(e.Value.ToString());
            e.Value = d.ToString("0.00##");
        }
    } 

SOURCE: http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/95e7e7ef-2e71-412f-abe5-ffbee2c12c18/

OUTPUT:

Example Output from application

Undersell answered 27/6, 2012 at 15:45 Comment(5)
in console application works but in DataGridview columns not work. I am try this in the event _CellFormatingAdlare
What does it output or show in the DataGridview using this string? "does not work" is not clear.Undersell
is not working properly, the mask "0.00##" work as "n2" only get 2 decimalsAdlare
thank you so much, I really liked your example, I was wrong, between the 2000 lines of code I saw that another event was interfering.Adlare
It is easy to lose that sometimes. :) Glad you could get it to work. I also learned a lot on this, great question!Undersell
U
2

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

Undersell answered 27/6, 2012 at 15:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.