Custom Column Value Formatter

3 posts, 1 answers
  1. Vinoth Kathappanraju
    Vinoth Kathappanraju avatar
    3 posts
    Member since:
    Mar 2010

    Posted 14 Jun Link to this post

    Hi

    I have a requirement where i need to pass in a custom formatter for values in a GridViewDataColumn. I looked at DataFormatString but i don't think it satisfies my requirement.My requirement is that i need to round the decimal to 4 decimal places but also show a negative sign if the number is negative. For example, if the number is -0.000001, then my grid should show -0.0000 and not just 0.0000. For a positive number, it should just display 0.0000. How do i get this working? Any help is much appreciated.

     

    Thanks

    Vinoth

  2. Answer
    Dilyan Traykov
    Admin
    Dilyan Traykov avatar
    368 posts

    Posted 16 Jun Link to this post

    Hello Vinoth,

    To achieve the desired behavior, you will need to set a converter for your binding and handle the rounding manually as, by default, the result you're getting is expected. Here's an example:

    public class DecimalToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var number = (decimal)value;
            var shouldAddNegativeSign = number < 0 && number >= -0.00005M;
            var numberAsString = string.Format("{0}{1:F4}", shouldAddNegativeSign ? "-" : "", number);
     
            return numberAsString;
        }
     
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    <telerik:GridViewDataColumn DataMemberBinding="{Binding StadiumCapacity, Converter={StaticResource DecimalToStringConverter}}" />

    Would such an approach be suitable for your scenario?

    Regards,
    Dilyan Traykov
    Telerik
    Do you need help with upgrading your AJAX, WPF or WinForms project? Check the Telerik API Analyzer and share your thoughts.
  3. UI for WPF is Visual Studio 2017 Ready
  4. Vinoth Kathappanraju
    Vinoth Kathappanraju avatar
    3 posts
    Member since:
    Mar 2010

    Posted 28 Jun in reply to Dilyan Traykov Link to this post

    Thanks Dilyan. This works great and satisfies my current requirement.

     

    Thanks

    Vinoth

Back to Top