本文介绍了如何在DataGridView中用最大值和最小值格式化带有十进制数字的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想格式化在 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)

在 DataGridView 列中txtcDecimal"具有属性(来自设计器)

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

掩码0.00##"作为n2"只得到2位小数它正确四舍五入到两位小数,但不喜欢我需要的(如我在示例中所示)

the mask "0.00##" work as "n2" only get 2 decimalswhich 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?

感谢 harlam357 &汤姆·加尔斯克

推荐答案

要格式化 2 到 4 位小数,您可以使用自定义格式字符串.

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

txtcDecimal.DefaultCellStyle.Format = "0.00##"

再进一步...

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; }
   }
}

这篇关于如何在DataGridView中用最大值和最小值格式化带有十进制数字的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 14:05