c# - 如何在 DataGridView 中格式化带有最大值和最小值的小数列?

标签 c# .net winforms string datagridview

我想格式化在 DataGridView 中显示和捕获的小数位,我有最小小数位数和最大小数位数。 例如:

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”具有属性(来自设计器)

txtcDecimal.DefaultCellStyle.Format = "N2";

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

掩码“0.00##”作为“n2”只能得到两位小数 它正确地四舍五入到小数点后两位,但不符合我的需要(如我在示例中所示)

如何在不消耗大量资源的情况下以简单的方式做到这一点?

感谢 harlam357 和 Tom Garske

最佳答案

要在 2 到 4 位小数之间设置格式,您可以使用自定义格式字符串。

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

关于c# - 如何在 DataGridView 中格式化带有最大值和最小值的小数列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11229590/

相关文章:

c# - JavaScriptSerializer - 如何反序列化名称中带有破折号 ("-") 的属性?

c# - 通用查找函数作为参数

c# - 使用 .NET 从 FileStream 的特定位置读取数据

c# - 在 Datagridview 中删除整行

C# Mysql 与 Entity Framework 错误 - 无法更新 EDMX 文件

c# - 如何使用 join 加速 LINQ 查询?

c# - 将小数(2.75)转换为时间(2 :45)

html - 如何删除字符串生成器表中的神秘边框?

C# WebKit 和 CKEditor iframe 抓取

c# - 使 Windows 窗体可扩展的最佳方式?