Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Formatting Price with IFormattable, IFormatProvider, and NumberFormatInfo

Define the `Price.ToString` contract, pass numeric settings through to `decimal`, and change the decimal separator on a writable copy rather than on the original.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

System.IFormattable: string ToString(string? format, IFormatProvider? formatProvider);
System.IFormatProvider: object? GetFormat(Type? formatType);
System.Globalization.NumberFormatInfo: public object Clone();
Writable copy: var copy = (NumberFormatInfo)source.Clone();
Direct call: price.ToString("F2", copy)
Composite call: string.Format(copy, "{0:F2}", price)

System.IFormattable defines the two-argument ToString(format, formatProvider) method. An implementation must support the general format G and accept null to select its default format. The parameterless ToString() is a separate override of object.ToString(). In this example, it delegates to the same implementation with both arguments set to null.

Price decides which formats it accepts: null, the empty string, G, and g select the general decimal format; F2 and f2 produce exactly two fractional digits with no digit grouping or currency symbol. Other formats throw FormatException. Formatting changes the text, not the stored amount.

System.IFormatProvider supplies settings; it does not format the amount. GetFormat(Type?) returns an object of the requested type or null if it cannot supply one. When formatting a decimal, CultureInfo supplies its NumberFormat settings, and System.Globalization.NumberFormatInfo can return itself. With a null provider or one that supplies no numeric settings, decimal uses the current culture. The example's string.Format call passes F2 and the copy to the Price implementation of IFormattable.ToString.

NumberFormatInfo.InvariantInfo is read-only; setting NumberDecimalSeparator on it throws InvalidOperationException. Clone() returns a writable shallow copy as object. Cast it to NumberFormatInfo and change the separator on the copy. Passing the copy to a call does not change the original or the current culture.

Examples

#nullable enable
using System;
using System.Globalization;

var price = new Price(1234.5m);
var original = NumberFormatInfo.InvariantInfo;
var copy = (NumberFormatInfo)original.Clone();
copy.NumberDecimalSeparator = ",";

IFormattable formattable = price;
Console.WriteLine(formattable.ToString(null, original));
Console.WriteLine(string.Format(copy, "{0:F2}", price));
Console.WriteLine(price.ToString("F2", original));

public sealed class Price(decimal amount) : IFormattable
{
    public override string ToString() => ToString(null, null);

    public string ToString(string? format, IFormatProvider? formatProvider)
        => format switch
        {
            null or "" or "G" or "g" => amount.ToString("G", formatProvider),
            "F2" or "f2" => amount.ToString("F2", formatProvider),
            _ => throw new FormatException("Unsupported Price format.")
        };
}

Result

1234.5
1234,50
1234.50

The first line shows the default chosen by a `null` format. The last two use `F2`: the comma comes from the copy, and the dot comes from the unchanged original.

Related lessons

  • C# · Lesson 33 · Intermediate · Version: 2

Sources