The Global String Formatter library allows developers to deal with conditional string formatting in an elegant fashion. Developers specify a predicate and a corresponding string output function for each case of the formatting. GString plays well with dependency-injection frameworks.

A short example

As part of an online annual sales report, you would like to output the sales figure differently depending on its value:

  • ${X.XX} for sales < $10,000 (i.e. $101.35)
  • ${X.XX}k for sales >= $10,000 and < $1,000,000 (i.e. $12.61k, $372.89k)
  • ${X.XX)m for sales >= $1,000,000 (i.e. $9.37m, $87.52m)

The GString Way

Global String (GString) Formatter gives developers the option of defining variables like sales declaratively. Once initialized with a conditional set of string formats, any GString of that type will be outputted the same way, without need to pass the value through any functions. Here is the GString way of formatting sales.

Define your GString type and any formatters. (Note that the Currency class is just a way to do book-keeping. It helps keep your GString class distinct from GString<Temperature, double>)

public class Currency {}
public class USDGString : GString<Currency, double>
	public USDGString()
		Formatters.Add(v => v < 1000, v => string.Format("{0:C}", v));
		Formatters.Add(v => v >= 1000 && v < 1000000, v => string.Format("{0:C}k", v / 1000));
		Formatters.Add(v => v >= 1000000, v => string.Format("{0:C}m", v / 1000000));


The CompanyAccount class:

public class CompanyAccount
	public USDGString Sales { get; private set; }
	public CompanyAccount(double sales)
		Sales = new USDGString() { Value = sales };


To create a CompanyAccount:

var companyAccount = new CompanyAccount(8300291);


Printing the value by console would produce the desired formatted output:

Console.Writeline(companyAccount.Sales); // prints $8.30m

More info

For more examples as well as advanced usage with dependency injection, see:

Last edited Feb 1, 2011 at 12:27 AM by jookyboi, version 14