C# Numeric Format Strings


This entry is part 8 of 10 in the series C# Getting Started

Standard C# numeric format strings are used to format common numeric types. Microsoft has a web page on this topic that is called Standard Numeric Format Strings. The format field specifies the form that the numeric representation should take. For example, should it be represented as currency, in decimal format, in hexadecimal format, or in fixed-point notation?

  • The colon character must be next to the format specifier, with no intervening spaces.
  • The format specifier is a single alphabetic character, from a set of nine built-in character formats. The character can be uppercase or lowercase. The case is significant for some specifiers but not for others.
  • The precision specifier is optional and consists of one or two digits. Its actual meaning depends on the format specifier.

Below is some sample code. The number 15 represent the number of spaces. Positive 15 means right-align. If we had -15 then it would be left aligned. This is very useful if you are displaying a list of numbers on the console.

float myFloat = 12.5f;
float myFloat2 = 198.56f;
Console.WriteLine($"{myFloat,15:C}");
Console.WriteLine($"{myFloat2,15:C}");

Below is a screenshot of the results.

Notice that we have used string interpolation in this above example. The dollar sign is the indication of that.

Series Navigation<< C# StatementsC# Keywords >>