Implements ICustomFormatter : ICustomFormatter « Class Interface « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Design Patterns
8.Development Class
9.Event
10.File Stream
11.Generics
12.GUI Windows Form
13.Language Basics
14.LINQ
15.Network
16.Office
17.Reflection
18.Regular Expressions
19.Security
20.Services Event
21.Thread
22.Web Services
23.Windows
24.Windows Presentation Foundation
25.XML
26.XML LINQ
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » Class Interface » ICustomFormatterScreenshots 
Implements ICustomFormatter
 

using System;
using System.Text;

using System.Globalization;
public class WordyFormatProvider : IFormatProvider, ICustomFormatter {
    static readonly string[] _numberWords = "zero one two three four five six seven eight nine minus point".Split();

    IFormatProvider _parent;   // Allows consumers to chain format providers

    public WordyFormatProvider() this(CultureInfo.CurrentCulture) { }
    public WordyFormatProvider(IFormatProvider parent) {
        _parent = parent;
    }

    public object GetFormat(Type formatType) {
        if (formatType == typeof(ICustomFormatter)) return this;
        return null;
    }

    public string Format(string format, object arg, IFormatProvider prov) {
        if (arg == null || format != "W")
            return string.Format(_parent, "{0:" + format + "}", arg);

        StringBuilder result = new StringBuilder();
        string digitList = string.Format(CultureInfo.InvariantCulture,
                                          "{0}", arg);
        foreach (char digit in digitList) {
            int i = "0123456789-.".IndexOf(digit);
            if (i == -1continue;
            if (result.Length > 0result.Append(' ');
            result.Append(_numberWords[i]);
        }
        return result.ToString();
    }
}


public class MainClass {
    public static void Main() {

        double n = -123.45;
        IFormatProvider fp = new WordyFormatProvider();
        Console.WriteLine(string.Format(fp, "{0:C} in words is {0:W}", n));
    }
}

 
Related examples in the same category
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.