How to: Create a Custom Formatter to Represent Decimal Values in Binary

  • 2 minutes to read

This example demonstrates a way of creating a custom formatter object to display decimal values in binary, but only if the format string is supplied as "B".

The result is shown in the image below.


// A custom formatter object.
public class BaseFormatter : IFormatProvider, ICustomFormatter {
    // The GetFormat method of the IFormatProvider interface.
    // This must return an object that provides formatting services for the specified type.
    public object GetFormat(Type format) {
        if (format == typeof (ICustomFormatter)) return this;
        else return null;
    // The Format method of the ICustomFormatter interface.
    // This must format the specified value according to the specified format settings.
    public string Format (string format, object arg, IFormatProvider provider) {
        if (format == null) {
            if (arg is IFormattable)
                return ((IFormattable)arg).ToString(format, provider);
                return arg.ToString(); 
        if (format == "B")
            return Convert.ToString(Convert.ToInt32(arg), 2);
            return arg.ToString();

// ...
// Assign the custom formatter to the editor.
spinEdit1.Properties.DisplayFormat.FormatType = FormatType.Custom;
spinEdit1.Properties.DisplayFormat.FormatString = "B";
spinEdit1.Properties.DisplayFormat.Format = new BaseFormatter();
spinEdit1.Properties.IsFloatValue = false;
spinEdit1.EditValue = 10;