Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 139 additions & 0 deletions UnitsNet.Tests/QuantityFormatterTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen ([email protected]). Maintained at https://github.com/angularsen/UnitsNet.

using Xunit;

namespace UnitsNet.Tests
{
public class QuantityFormatterTests
{
[Theory]
[InlineData("C")]
[InlineData("C0")]
[InlineData("C1")]
[InlineData("C2")]
[InlineData("C3")]
[InlineData("C4")]
[InlineData("C5")]
[InlineData("C6")]
[InlineData("c")]
[InlineData("c0")]
[InlineData("c1")]
[InlineData("c2")]
[InlineData("c3")]
[InlineData("c4")]
[InlineData("c5")]
[InlineData("c6")]
[InlineData("E")]
[InlineData("E0")]
[InlineData("E1")]
[InlineData("E2")]
[InlineData("E3")]
[InlineData("E4")]
[InlineData("E5")]
[InlineData("E6")]
[InlineData("e")]
[InlineData("e0")]
[InlineData("e1")]
[InlineData("e2")]
[InlineData("e3")]
[InlineData("e4")]
[InlineData("e5")]
[InlineData("e6")]
[InlineData("F")]
[InlineData("F0")]
[InlineData("F1")]
[InlineData("F2")]
[InlineData("F3")]
[InlineData("F4")]
[InlineData("F5")]
[InlineData("F6")]
[InlineData("f")]
[InlineData("f0")]
[InlineData("f1")]
[InlineData("f2")]
[InlineData("f3")]
[InlineData("f4")]
[InlineData("f5")]
[InlineData("f6")]
[InlineData("N")]
[InlineData("N0")]
[InlineData("N1")]
[InlineData("N2")]
[InlineData("N3")]
[InlineData("N4")]
[InlineData("N5")]
[InlineData("N6")]
[InlineData("n")]
[InlineData("n0")]
[InlineData("n1")]
[InlineData("n2")]
[InlineData("n3")]
[InlineData("n4")]
[InlineData("n5")]
[InlineData("n6")]
[InlineData("P")]
[InlineData("P0")]
[InlineData("P1")]
[InlineData("P2")]
[InlineData("P3")]
[InlineData("P4")]
[InlineData("P5")]
[InlineData("P6")]
[InlineData("p")]
[InlineData("p0")]
[InlineData("p1")]
[InlineData("p2")]
[InlineData("p3")]
[InlineData("p4")]
[InlineData("p5")]
[InlineData("p6")]
[InlineData("R")]
[InlineData("R0")]
[InlineData("R1")]
[InlineData("R2")]
[InlineData("R3")]
[InlineData("R4")]
[InlineData("R5")]
[InlineData("R6")]
[InlineData("r")]
[InlineData("r0")]
[InlineData("r1")]
[InlineData("r2")]
[InlineData("r3")]
[InlineData("r4")]
[InlineData("r5")]
[InlineData("r6")]
public static void StandardNumericFormatStrings_Equals_ValueWithFormatStringAndAbbreviation(string format)
{
var length = Length.FromMeters(123456789.987654321);

var expected = string.Format($"{{0:{format}}} {{1:a}}", length.Value, length);
Assert.Equal(expected, QuantityFormatter.Format(length, format));
}

[Theory]
[InlineData("000")]
[InlineData("0.00")]
[InlineData("#####")]
[InlineData("#.##")]
[InlineData("##,#")]
[InlineData("#,#,,")]
[InlineData("%#0.00")]
[InlineData("##.0 %")]
[InlineData("#0.00‰")]
[InlineData("#0.0e0")]
[InlineData("0.0##e+00")]
[InlineData("0.0e+00")]
[InlineData(@"\###00\#")]
[InlineData("#0.0#;(#0.0#);-\0-")]
[InlineData("#0.0#;(#0.0#)")]
public static void CustomNumericFormatStrings_Equals_ValueWithFormatStringAndAbbreviation(string format)
{
var length = Length.FromMeters(123456789.987654321);

var expected = string.Format($"{{0:{format}}} {{1:a}}", length.Value, length);
Assert.Equal(expected, QuantityFormatter.Format(length, format));
}
}
}
121 changes: 87 additions & 34 deletions UnitsNet/QuantityFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,37 @@ namespace UnitsNet
/// </summary>
public class QuantityFormatter
{
/// <summary>
/// The available UnitsNet custom format specifiers.
/// </summary>
private static readonly char[] UnitsNetFormatSpecifiers = { 'A', 'a', 'G', 'g', 'Q', 'q', 'S', 's', 'U', 'u', 'V', 'v' };

/// <summary>
/// Formats the given quantity using the given format string. Uses the <see cref="CultureInfo.CurrentUICulture" />.
/// </summary>
/// <typeparam name="TUnitType">The quantity's unit type, for example <see cref="LengthUnit"/>.</typeparam>
/// <param name="quantity">The quantity to format.</param>
/// <param name="format">The format string.</param>
/// <remarks>
/// The valid format strings are as follows:
/// Any of the standard numeric format strings for double values except for "G" or "g" ("C" or "c", "E" or "e", "F" or "f", "N" or "n", "P" or "p", "R" or "r").
/// "G" or "g": The value with 2 significant digits after the radix followed by the unit abbreviation, such as "1.23 m".
/// "A" or "a": The default unit abbreviation for <see cref="IQuantity{TUnitType}.Unit" />, such as "m".
/// "a0", "a1", ..., "aN": The Nth unit abbreviation for <see cref="IQuantity{TUnitType}.Unit" />. "a0" is the same as "a".
/// A <see cref="FormatException"/> will be thrown if the requested abbreviation index does not exist.
/// "V" or "v": String representation of <see cref="IQuantity.Value" />.
/// "U" or "u": The enum name of <see cref="IQuantity{TUnitType}.Unit" />, such as "Meter".
/// "Q" or "q": The quantity name, such as "Length".
/// "s1", "s2", ..., "sN": The value with N significant digits after the radix followed by the unit abbreviation. For example,
/// "s4" would return "1.2345 m" if <see cref="IQuantity.Value" /> is 1.2345678. Trailing zeros are omitted.
/// </remarks>
/// <returns>The string representation.</returns>
public static string Format<TUnitType>(IQuantity<TUnitType> quantity, string format)
where TUnitType : Enum
{
return Format(quantity, format, CultureInfo.CurrentUICulture);
}

/// <summary>
/// Formats the given quantity using the given format string and format provider.
/// </summary>
Expand All @@ -23,13 +54,14 @@ public class QuantityFormatter
/// <see cref="CultureInfo.CurrentUICulture" /> if null.</param>
/// <remarks>
/// The valid format strings are as follows:
/// "g": The value with 2 significant digits after the radix followed by the unit abbreviation, such as "1.23 m".
/// "a": The default unit abbreviation for <see cref="IQuantity{TUnitType}.Unit" />, such as "m".
/// Any of the standard numeric format strings for double values except for "G" or "g" ("C" or "c", "E" or "e", "F" or "f", "N" or "n", "P" or "p", "R" or "r").
/// "G" or "g": The value with 2 significant digits after the radix followed by the unit abbreviation, such as "1.23 m".
/// "A" or "a": The default unit abbreviation for <see cref="IQuantity{TUnitType}.Unit" />, such as "m".
/// "a0", "a1", ..., "aN": The Nth unit abbreviation for <see cref="IQuantity{TUnitType}.Unit" />. "a0" is the same as "a".
/// A <see cref="FormatException"/> will be thrown if the requested abbreviation index does not exist.
/// "v": String representation of <see cref="IQuantity.Value" />.
/// "u": The enum name of <see cref="IQuantity{TUnitType}.Unit" />, such as "Meter".
/// "q": The quantity name, such as "Length".
/// "V" or "v": String representation of <see cref="IQuantity.Value" />.
/// "U" or "u": The enum name of <see cref="IQuantity{TUnitType}.Unit" />, such as "Meter".
/// "Q" or "q": The quantity name, such as "Length".
/// "s1", "s2", ..., "sN": The value with N significant digits after the radix followed by the unit abbreviation. For example,
/// "s4" would return "1.2345 m" if <see cref="IQuantity.Value" /> is 1.2345678. Trailing zeros are omitted.
/// </remarks>
Expand All @@ -39,41 +71,62 @@ public static string Format<TUnitType>(IQuantity<TUnitType> quantity, string for
{
formatProvider = formatProvider ?? CultureInfo.CurrentUICulture;

var number = 0;
var formatString = format;

if(string.IsNullOrEmpty(formatString))
formatString = "g";
if(string.IsNullOrEmpty(format))
format = "g";

if(formatString.StartsWith("a") || formatString.StartsWith("s"))
if(UnitsNetFormatSpecifiers.Any(c => c == format[0]))
{
if(formatString.Length > 1 && !int.TryParse(formatString.Substring(1), out number))
throw new FormatException($"The {format} format string is not supported.");
// UnitsNet custom format string

formatString = formatString.Substring(0, 1);
}
int precisionSpecifier = 0;
char formatSpecifier = format[0];

switch(formatString)
{
case "g":
return ToStringWithSignificantDigitsAfterRadix(quantity, formatProvider, 2);
case "a":
var abbreviations = UnitAbbreviationsCache.Default.GetUnitAbbreviations(quantity.Unit, formatProvider);
switch(formatSpecifier)
{
case 'A':
case 'a':
case 'S':
case 's':
if(format.Length > 1 && !int.TryParse(format.Substring(1), out precisionSpecifier))
throw new FormatException($"The {format} format string is not supported.");
break;
}

switch(formatSpecifier)
{
case 'G':
case 'g':
return ToStringWithSignificantDigitsAfterRadix(quantity, formatProvider, 2);
case 'A':
case 'a':
var abbreviations = UnitAbbreviationsCache.Default.GetUnitAbbreviations(quantity.Unit, formatProvider);

if(number >= abbreviations.Length)
throw new FormatException($"The {format} format string is invalid because the abbreviation index does not exist.");
if(precisionSpecifier >= abbreviations.Length)
throw new FormatException($"The {format} format string is invalid because the abbreviation index does not exist.");

return abbreviations[precisionSpecifier];
case 'V':
case 'v':
return quantity.Value.ToString(formatProvider);
case 'U':
case 'u':
return quantity.Unit.ToString();
case 'Q':
case 'q':
return quantity.QuantityInfo.Name;
case 'S':
case 's':
return ToStringWithSignificantDigitsAfterRadix(quantity, formatProvider, precisionSpecifier);
default:
throw new FormatException($"The {format} format string is not supported.");
}
}
else
{
// Anything else is a standard numeric format string with default unit abbreviation postfix.

return abbreviations[number];
case "v":
return quantity.Value.ToString(formatProvider);
case "u":
return quantity.Unit.ToString();
case "q":
return quantity.QuantityInfo.Name;
case "s":
return ToStringWithSignificantDigitsAfterRadix(quantity, formatProvider, number);
default:
throw new FormatException($"The {format} format string is not supported.");
var abbreviations = UnitAbbreviationsCache.Default.GetUnitAbbreviations(quantity.Unit, formatProvider);
return string.Format(formatProvider, $"{{0:{format}}} {{1}}", quantity.Value, abbreviations.First());
}
}

Expand Down