« Tired of the Apple iPhone yet? | Main | Adobe Lightroom 1.0 - $199 US till April 30, 2007 »

How to display a formatted number in WPF

I needed to format a double into a sane format for an application I'm working on.

The data is somewhat more precise than I need.

I wanted to format the exposure time more reasonably with only a few decimal points rather than the 4000 digit number I seemed to be getting ... . So, a handy value Converter was needed to fix the problem:

    [ValueConversion(typeof(object), typeof(string))]
    public class ToStringFormatConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string fmt = parameter as string;
            if (!string.IsNullOrEmpty(fmt))
            {
                return string.Format(culture, fmt, value);
            }
            else
            {
                return value.ToString();
            }
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
        
    }

Then, using Binding and the Converter:

<TextBlock Text="{Binding Path=ExposureTime, Converter={StaticResource stringFormatConverter}, ConverterParameter={}{0:#0.0##}}" />

I needed to add to the resources section of my XAML file, an instance of this object:

<local:ToStringFormatConverter x:Key="stringFormatConverter"/>

The local namespace was added to the Window class (it could be added to any other root level WPF element like a page, etc):

xmlns:local="clr-namespace:MyApplicationNamespace"

To adjust the format, just change the ConverterParameter format shown above in red ({0:#0.0##}). This is just the normal ToString formatters that you have available in any .NET application. No gimmicks. The leading curly braces {} are used to escape the remainder of the string.

The ValueConversion attribute on the class I created is used to indicate to development environments and tools what types of inputs and outputs are expected to the function. In this case, it's always a string out, but the in varies.

Here was the result:

A nicely formatted number.

Comments

Hi Aaron - I like your converter :-). I'm curious as to why you think the \{ \} way of escaping the curly braces is less correct than using {} (as you commented in my quite-similar article)? Both techniques seem to work.

As far as I know, the {} is the preferred technique and is well documented in the current versions.

Help support my web site by searching and buying through Amazon.com (in assocation with Amazon.com).