Table of Contents

Class UnitFormatter

Namespace
Codebelt.Unitify
Assembly
Codebelt.Unitify.dll

Defines the string formatting of objects having an implementation of IUnit.

Examples

Format units with custom numeric representations and culture-specific formatting. This example demonstrates creating units with different base values, shows the default string representation, applies custom format options via the factory method, and demonstrates using a UnitFormatter instance for explicit formatting with a specific CultureInfo:

using System;
using System.Globalization;
using Codebelt.Unitify;

namespace Unitify.Samples;

public class UnitFormatterExample
{
    public static void Main()
    {
        // Create units with different values
        var watt = UnitFactory.CreateWatt(1234.5);
        var kilowatt = UnitFactory.CreateWatt(1234.5, DecimalPrefix.Kilo);
        
        // Display default string representation
        Console.WriteLine($"1 Watt: {watt}");
        Console.WriteLine($"1 Kilowatt: {kilowatt}");
        
        // Create a unit with custom formatting options
        var formattedWatt = UnitFactory.CreateWatt(1234.5, setup: options =>
        {
            options.NumberFormat = "N2";
            options.Style = NamingStyle.Compound;
        });
        
        Console.WriteLine($"With custom formatting: {formattedWatt}");
        
        // Create a formatter instance for custom formatting scenarios
        var formatter = new UnitFormatter();
        string customFormat = formatter.Format("Power: {0:F1}", watt, CultureInfo.InvariantCulture);
        Console.WriteLine(customFormat);
    }
}
public class UnitFormatter : IFormatProvider, ICustomFormatter
Inheritance
UnitFormatter
Implements

Methods

Format(string, object, IFormatProvider)

Converts the value of a specified arg to an equivalent string representation using specified format and culture-specific format formatProvider.

public string Format(string format, object arg, IFormatProvider formatProvider)

Parameters

format string

A format string containing formatting specifications.

arg object

An object that implements the IUnit interface.

formatProvider IFormatProvider

An object that supplies format information about arg.

Returns

string

The string representation of the value of arg, formatted as specified by format and formatProvider.

GetFormat(Type)

Returns an object that provides formatting services for the specified type.

public object GetFormat(Type formatType)

Parameters

formatType Type

An object that specifies the type of format object to return.

Returns

object

An instance of the object specified by formatType, if the IFormatProvider implementation can supply that type of object; otherwise, null.

See Also