Working With Numeric Format Specifiers in C# 10

Developers can make use of numeric format specifiers in Console.WriteLine() statements in C# when working with numeric data.

Typical syntax for a standard numeric format string is:

format specifier][precision specifier]

where:

  • format specifier:  a single alphabetic character specifying type of number format, such as currency or percent.
  • precision specifier: an optional integer that affects number of digits in the resulting string. .NET 7.0 onwards, the maximum precision value is 999,999,999. Note that the precision specifier only controls the number of digits in the string representation of a number. It does not round the number itself.

Any numeric format string that contains more than one alphabetic character, including white space, is interpreted as a custom numeric format string. For example, a numeric format specifier can be suffixed with digits specifying number of zeros to be inserted after a decimal location. If you use a specifier such as C2, two zeros will be suffixed after the decimal location of the given number.

The following table lists some of the standard and custom numeric format specifiers that you have in C#

Format Specifier Standard/Custom Description
C or c Standard A standard numeric format for Currency. The number is converted to a string that represents a currency amount.
D or d Standard A standard numeric format for Decimal. The number is converted to a string of decimal digits (0-9), prefixed by a minus sign in case the number is negative. The precision specifier indicates the minimum number of digits desired in the resulting string. This format is supported for fundamental types only.
E or e Standard A standard numeric format for Scientific (Exponential). The number is converted to a string of the form ‘-d. ddd...E+ddd’ or ‘-d.ddd...e+ddd’, where each ‘d’ indicates a digit (0-9).
F or f Fixed-point The number is converted to a string of the form ‘-ddd. ddd...’ where each ‘d’ indicates a digit (0-9). If the number is negative, the string starts with a minus sign.
N or n Number The number is converted to a string of the form ‘-d,ddd,ddd.ddd...’, where each ‘d’ indicates a digit (0- 9). If the number is negative, the string starts with a minus sign.
X or x Hexadecimal The number is converted to a string of hexadecimal digits. It uses "X" to produce "ABCDEF", and "x" to produce "abcdef.
G or g Standard A standard numeric format for General format. It converts a number to the more compact of either fixed-point or scientific notation, depending on type of the number and whether a precision specifier is present. If the precision specifier is not present or zero, the type of the number determines the default precision.
0 Custom It serves as a zero-placeholder symbol. If the value being formatted contains a digit where ‘0’ appears, then it is copied to the result string.
# Custom It serves as a digit-placeholder symbol. If the value being formatted contains a digit where ‘#’ appears, then, it is copied to the result string.
. Custom The first ‘.’ character verifies the location of the decimal separator.
, Custom The ‘,’ character serves as a thousand separator specifier and a number scaling specifier.
% Custom The ‘%’ character in a format string multiplies a number with 100 before it is formatted.
; Custom The ‘;’ character separates a section into positive, negative, and zero numbers
E0, E+0,E-0, e0, e+0, e-0 Custom If any of the given strings are present in the format string and they are followed by at least one ‘0’ character, then the number is formatted using scientific notation.
\ Custom The backslash character causes the next character in the format string to be interpreted as an escape sequence.
‘ABC’  or "ABC" Custom The characters that are enclosed within single or double quotes are copied to the result string.

The following code demonstrates the conversion of a numeric value using C, D, and E format specifiers. Create a C# based Console App using Visual Studio 2022 and then, add the following code inside Program.cs. Then, click Debug > Start Without Debugging. Alternatively, create a class using any other editor and then, run it at the command prompt.

using System;
using System.Globalization;
namespace ConsoleApp1 {
    internal class Program {
        static void Main(string[] args) {
            //set output encoding so that ₹ is displayed
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            CultureInfo ci = CultureInfo.CurrentCulture;
            // Display the name of the current culture to verify
            // current culture is India.
            Console.WriteLine("CurrentCulture is {0}.",
                CultureInfo.CurrentCulture.Name);
            int num = 934;
            Console.WriteLine("{0:C}", num);
            Console.WriteLine("{0:D}", num);
            Console.WriteLine("{0:E}", num);
        }
    }
}

What we did here: The current culture on the local system where the code is executed is India (en-IN). By default, the ₹ is not displayed as currency symbol because of output encoding. Hence, we first set output encoding using the statement

Console.OutputEncoding = System.Text.Encoding.UTF8;

so that ₹ is displayed.

Then, we assigned a value of 934 to a variable num. After this, we applied numeric format specifiers C, D and E respectively to num and displayed the outcomes.

What it produces

Let's look at another example.

using System;
class Test {
    static void Main(string[] args) {
        int num = 934;
        Console.WriteLine("{0:F}", num);
        Console.WriteLine("{0:N}", num);
        Console.WriteLine("{0:X}", num);
        Console.WriteLine("{0:P}", num);
    }
}

What we did here: In this code, we aren't using any currency based format specifier so we can skip the encoding statements. We use the format specifiers F, N, and P to produce respective outcomes.

What it produces

Let's now use some custom numeric format specifiers. Here, we suffix the standard numeric format specifiers with certain digits so as to produce specific outcomes.  

using System;
using System.Globalization;
class Test {
    static void Main(string[] args) {
        double scorepoints = 56269.77451;
        //set output encoding so that ₹ is displayed
        Console.OutputEncoding = System.Text.Encoding.UTF8;
        CultureInfo ci = CultureInfo.CurrentCulture;
        Console.WriteLine("E:{0}", scorepoints.ToString("E03", ci));
        Console.WriteLine("F: {0}", scorepoints.ToString("F04", ci));
        Console.WriteLine("N: {0}", scorepoints.ToString("N03", ci));
        Console.WriteLine("P: {0}", (scorepoints / 10000).ToString("P02", ci));
        int rate = 7439;
        Console.WriteLine("D: {0}", rate.ToString("D6", ci));
        Console.WriteLine("E: {0}", rate.ToString("E03", ci));
        Console.WriteLine("F: {0}", rate.ToString("F01", ci));
        Console.WriteLine("N: {0}", rate.ToString("N01", ci));
        Console.WriteLine("P: {0}", (rate / 10000.0).ToString("P02", ci));
        Console.WriteLine();
    }
}

What it produces

Conclusion

This is how we can make use of standard and custom numeric format specifiers with Console.WriteLine to customize our numeric outputs.

You might find it useful to know that Microsoft has made available a .NET Core C# based Windows Forms application that allows you to apply standard or custom format strings to either numeric values or date and time values and to determine how they affect the result string. It is called as .NET Formatting Utility (Formatter.exe) and you can discover more about it here:

https://learn.microsoft.com/en-us/samples/dotnet/samples/windowsforms-formatting-utility-cs/


Similar Articles