避免在Datagridview控件中舍入小数

本文关键字:舍入 小数 控件 Datagridview | 更新日期: 2023-09-27 18:14:22

在Datagridview中,我有一个列"C",这是列" a ""B"的乘积。例子A列值- 8.14B列值- 0.2现在,列C的值是12.296,在十进制之后,我想显示前两个数字如下12.29 不舍入 12.30

下面是我用来实现上述结果的代码:

public class CustomFormatter : 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 (arg == null) return null;
        string numericString = arg.ToString();
        decimal result = 0;
        if (Decimal.TryParse(numericString, out result))
        {
            return ((Math.Truncate(result * 100)) / 100).ToString();
        }
        else
        {
            return null;
        }
    }
}
private void gvItemDetails_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    try
    {
        if (e.ColumnIndex == gvItemDetails.Columns["Vat Amount"].Index)
        {
            gvItemDetails[e.ColumnIndex, e.RowIndex].Value = String.Format(new CustomFormatter(), "{0}", e.Value);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

当我在单元格格式代码上放置断点时,我可以看到代码连续重复,但不返回任何stackoverflow异常。当我删除断点时,它可以工作。

你能告诉我可能的问题是什么,或者建议任何其他替代方法来防止显示12.29而不是12.30。

谢谢,Prathap .

避免在Datagridview控件中舍入小数

首先,我尝试使用您使用的相同方法。它对我来说工作得很好,并产生了理想的"12.29"。

string numericString = "12.2963";
string truncatedString = string.Empty;
decimal result = 0;
if (Decimal.TryParse(numericString, out result))
{
     truncatedString = ((Math.Truncate(result * 100)) / 100).ToString();
}

如果上面的方法不适合你,另一个简单的替代方法是使用string。子字符串(只有在不需要中间十进制值时才有用)。

string numericString = "12.2963";
string truncatedString = string.Empty;value
int endIndex = numericString.IndexOf('.');
truncatedString = numericString.Substring(0, endIndex + 3);
更新:

虽然我还没有测试过,但你应该可以这样定义格式提供程序:

this.dataGridView1.Columns["XYZ"].DefaultCellStyle.FormatProvider = new CustomFormatter();

和格式(这里格式字符串将具有预定义的含义):

this.dataGridView1.Columns["XYZ"].DefaultCellStyle.Format = "c"; 

更新2:不幸的是,即使你正在使用FormatProvider,你仍然需要处理cellformatting事件;检查这个。

好消息是,您不需要为此使用FormatProvider。尝试下面的格式,它应该为您工作:

this.dataGridView1.Columns["XYZ"].DefaultCellStyle.Format = "0.##";