Tarun
Tarun

Reputation: 393

How to format the decimal value with or without zeroes after decimal point c# 4.0 wpf datagrid

I want to display the decimal value without trailing zeroes if the decimal is a whole number i.e. if value is 10000000.00 then I am using the stringFormat="0,0.####" to display the value as 10,000,000. If the decimal value is 10000000.57 then it will display 10,000,000.57 which is fine. Now the issue is if the value is say 10000000.50 then its displays as 10,000,000.5 which is incorrect because of the stringFormat="0,0.####". The stringFormat I am using is mentioned in app.config file as below

<add source="currency1Amount"  headerText="Currency 1 Amount" filterType="textFilter" rowType="textRow" hasSpecifiedSource="" stringFormat="0,0.####" alignment="right"/>
    <add source="currency2Amount"  headerText="Currency 2 Amount" filterType="textFilter" rowType="textRow" hasSpecifiedSource="" stringFormat="0,0.####" alignment="right"/>

Apart from this, there are many columns that are getting displayed(values) at runtime means datagrid and mapping from server values are getting generated dynamically. So I dont have much control on values getting displayed in the above two columns.

Is it possible to define the stringFormat so that it fulfills my above requirement and solve the issue i.e if the value is 10000000.50 then it should display 10,000,000.50 not 10,000,000.5

Kindly help?

Upvotes: 0

Views: 1853

Answers (1)

Michael Mairegger
Michael Mairegger

Reputation: 7301

I think you can provide a IValueConverter

public class SpecialFormatting : IValueConverter
{
    public object Convert(object value, Type targetType, 
                          object parameter, CultureInfo culture)
    {
        double number = (double)value;
        if(number % 1 == 0)
            return string.Format("{0:N0}",number);
        return string.Format("{0:N2}",number);
    }

    public object ConvertBack(object value, Type targetType,
                              object parameter, CultureInfo culture)
    {
    }
}

And in WPF

<DataGrid>
    <DataGrid.Resources>
        <SpecialFormatting x:Key="SpecialFormattingConverter"/>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Path=MyNumber, 
            Converter={StaticResource SpecialFormattingConverter}}"/>
    </DataGrid.Columns>
</DataGrid>

Upvotes: 2

Related Questions