Skip to content

Instantly share code, notes, and snippets.

# yetanotherchris/gist:4774050 Created Feb 12, 2013

Inbuilt .NET formatting tokens
 // // In built formatters. These can have digit specifiers after them, such as {0:D5} // // Very similar to N (but no rounding), but with the currency symbol. See the section on regions. Console.WriteLine("a) [C]urrency - {0:C}", 1123.27); // Integers only. The '5' sets the number of zeros to pad to the left. Console.WriteLine("b) [D]ecimal - {0:D5}", 1123); // Fixed decimal places including rounding. Console.WriteLine("c) [F]ixed - {0:F3}", 1123.275); // Scientific or decimal notation, whichever is shorter. Has a long set of rules in MSDN. Console.WriteLine("d) [G]eneral - {0:G}", 1123.275); // Similar to fixed, but includes ',' thousand seperator and is rounded to 2 dp by default. Console.WriteLine("e) [N]umber - {0:N}", 1123.275); // Percentage to 2 dp. So 0.99998 is 100%. The number is multiplied by 100 in order to be presented as a percentage Console.WriteLine("f) [P]ercent - {0:P}", 0.2345); // This shows the percentage but as a whole number, rounded. The number is multiplied by 100 in order to be presented as a percentage Console.WriteLine("g) [P]ercent - {0:#%} ", 0.915); double d1 = 1234.9998; string rd = string.Format("{0:R}", d1); double d2 = Double.Parse(rd); Debug.Assert(d1 == d2); Console.WriteLine("h) [R]ound trip - {0:R}", 0.9998); // Allows you to parse the resulting string using Single.Parse() or Double.Parse() Console.WriteLine("i) he[X]adecimal - 0x{0:X}", 255); // Integers only Console.WriteLine("j) [E]xpontial - {0:E}", 10000000); Output: a) [C]urrency - £1,123.27 b) [D]ecimal - 01123 c) [F]ixed - 1123.275 d) [G]eneral - 1123.275 e) [N]umber - 1,123.28 f) [P]ercent - 23.45 % g) [P]ercent - 92% h) [R]ound trip - 0.9998 i) he[X]adecimal - 0xFF j) [E]xpontial - 1.000000E+007
to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.