Sometimes it is impossible to format values by using only String.Format pattern. For example, you may want to add ‘M’, ‘K’ and other suffixes to large numeric values to display them in the most compact form. When you do it, you have to provide means of converting strings with these suffixes back to numeric values. This is what formats are for. Please see below an example of creating arbitrary formats in an application below.

C# Copy imageCopy
//Ipmpelemtation of the custom format. 
//If the formatting value >= 1000, the resulting string will contain value, divised by 1000 with 'K' suffix
//If the formatting value >= 1000000, the resulting string will contain value, divised by 1000000 with 'M' suffix
public class SizeCustomFormat : IFormat
{
    public string Format(IDataField dataField)
    {
        decimal value = Convert.ToDecimal(dataField.Value);
        if (value >= 1000000)
        {
            value = value / 1000000;
            return value != 0 ? string.Format("{0:n2} M", value) : string.Empty;
        }
        if (value >= 1000)
        {
            value = value / 1000;
            return value != 0 ? string.Format("{0:n2} K", value) : string.Empty;
        }
        return value != 0 ? string.Format("{0:n2}", value) : string.Empty;
    }

    public bool CanParse(string text, IDataField dataField)
    {
        //verify, if the text can be parsed
        text = text.Replace("M", "");
        text = text.Replace("K", "");
        text = text.Trim();
        decimal value;
        if (!string.IsNullOrEmpty(text) && 
            decimal.TryParse(text, NumberStyles.Number | NumberStyles.Float | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out value))
        {
            return true;
        }
        return false;
    }

    public void Parse(string text, IDataField dataField)
    {
        //parse the text
        if(!string.IsNullOrEmpty(text))
        {
            decimal multiplier = 1;
            if(text.Contains("M"))
            {
                text = text.Replace("M", "");
                multiplier = 1000000;
            }
            else if (text.Contains("K"))
            {
                text = text.Replace("K", "");
                multiplier = 1000;
            }
            text = text.Trim();
            decimal value;
            if(decimal.TryParse(text, NumberStyles.Number|NumberStyles.Float|NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out value))
            {
                value *= multiplier;
                if (multiplier > 1)
                {
                    value = Decimal.Truncate(value);
                }

                //Set value to the field with the appropriate type
                dataField.Value = Convert.ChangeType(value, dataField.FieldType);
            }
        }
    }

    public object Clone()
    {
        return new SizeCustomFormat();
    }
}


//Some data object
public class Product
{
    private decimal price;

    [Format(typeof(SizeCustomFormat))]
    public decimal Price
    {
        get { return price; }
        set { price = value; }
    }
}


public void PopulateGrid(Grid grid)
{
    //Initialize the grid
    grid.Headers.Add(new Header());
    grid.Headers[0].Add(new Column("Price"));

    //By default, all grids use the formats are set trough the FormatAttribute.
    //Another way to set the format only for the specified column is to use the property Column.Format.
    //grid.Headers[0]["Price"].Format = new SizeCustomFormat();

    Product product = new Product();
    grid.Rows.Add(product);


    //Formatting data
    product.Price = 12469723.46654m;
    Console.WriteLine("The cell displays the text: {0}", grid.Rows[0]["Price"].Text);

    product.Price = 469723.46654m;
    Console.WriteLine("The cell displays the text: {0}", grid.Rows[0]["Price"].Text);

    product.Price = 723.46654m;
    Console.WriteLine("The cell displays the text: {0}", grid.Rows[0]["Price"].Text);

    //Parsing text
    grid.Rows[0]["Price"].Text = "123.654";
    Console.WriteLine("The product price: {0}", product.Price);

    grid.Rows[0]["Price"].Text = "123.654 K";
    Console.WriteLine("The product price: {0}", product.Price);

    grid.Rows[0]["Price"].Text = "123.654 M";
    Console.WriteLine("The product price: {0}", product.Price);
}

//Output:
//The cell displays the text: 12,47 M
//The cell displays the text: 469,72 K
//The cell displays the text: 723,47
//The product price: 123,654
//The product price: 123654
//The product price: 123654000

Back to .Net Grid HowTo topics