PluralFormatter.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. using System;
  2. namespace Quadarax.Foundation.Core.Value.Formatters
  3. {
  4. /// <summary>
  5. /// Formats a numeric value based on a format P:Plural:Singular
  6. /// </summary>
  7. public class PluralFormatter : ICustomFormatter, IFormatProvider
  8. {
  9. public string Format(string format, object arg, IFormatProvider formatProvider)
  10. {
  11. if (arg !=null)
  12. {
  13. var parts = format.Split(':'); // ["P", "Plural", "Singular"]
  14. if (parts[0] == "P") // correct format?
  15. {
  16. // which index postion to use
  17. int partIndex = (arg.ToString() == "1")?2:1;
  18. // pick string (safe guard for array bounds) and format
  19. return String.Format("{0} {1}", arg, (parts.Length>partIndex?parts[partIndex]:""));
  20. }
  21. }
  22. return String.Format(format, arg);
  23. }
  24. public object GetFormat(Type formatType)
  25. {
  26. return formatType == typeof(ICustomFormatter)?this:null;
  27. }
  28. }
  29. }