using Amphora; using System; using System.Globalization; using Tessera.Text; using UnitTestSharp; using Tessera.UnitTests.Text; using static Tessera.UnitTests.Text.TimeNotationSamples; namespace Tessera.UnitTests.Text { public class NumberFormatTests : TestFixture { public static string CountOf(NumberFormat format, long value) { var buffer = new char[format.MaxCountLength]; int end = format.WriteCount(value, buffer, 0); return new string(buffer, 0, end); } public static string FixedOf(NumberFormat format, double value, int decimals) { var buffer = new char[format.MaxFixedLength]; int end = format.WriteFixed(value, decimals, buffer, 0); return new string(buffer, 0, end); } public static string DecimalOf(NumberFormat format, decimal value, int decimals) { var buffer = new char[format.MaxFixedLength]; return new string(buffer, 0, format.WriteDecimal(value, decimals, buffer, 0)); } public static string UngroupedOf(NumberFormat format, decimal value, int decimals) { var buffer = new char[format.MaxFixedLength]; return new string(buffer, 0, format.WriteDecimalUngrouped(value, decimals, buffer, 0)); } public static NumberFormat WithSymbols(string group, string decimalSeparator, string exponent) { return new NumberFormat(group, 3, 3, "-", decimalSeparator, "NaN", "Infinity", exponent, ShortNotation.English); } public static string ScientificOf(NumberFormat format, double value, int digits) { var buffer = new char[format.MaxScientificLength]; int end = format.WriteScientific(value, digits, buffer, 0); return new string(buffer, 0, end); } public static string ShortOf(NumberFormat format, double value, int digits) { var buffer = new char[format.MaxShortLength]; int end = format.WriteShortExponent(value, digits, buffer, 0); return new string(buffer, 0, end); } public static string PercentOf(NumberFormat format, double fraction, int decimals) { var buffer = new char[format.MaxPercentLength]; int end = format.WritePercent(fraction, decimals, buffer, 0); return new string(buffer, 0, end); } public static string ClockOf(NumberFormat format, long seconds, ClockFormat clock = default) { var buffer = new char[format.MaxClockLength]; int end = format.WriteClock(seconds, clock, buffer, 0); return new string(buffer, 0, end); } public static string DurationOf(NumberFormat format, long seconds, DurationFormat duration = default) { var buffer = new char[format.MaxDurationLength]; int end = format.WriteDuration(seconds, duration, buffer, 0); return new string(buffer, 0, end); } public static NumberFormat WithPercent(PercentNotation percent) { return new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", ShortNotation.English, percent, TimeNotation.English); } public static NumberFormat WithTime(TimeNotation time) { return new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", ShortNotation.English, PercentNotation.English, time); } public static NumberFormat Grouping(string separator, int primarySize, int secondarySize, string minusSign) { return new NumberFormat(separator, primarySize, secondarySize, minusSign, ".", "NaN", "Infinity", "e", ShortNotation.English); } public static CultureInfo CultureWithGroupSizes(string separator, params int[] sizes) { var culture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); culture.NumberFormat.NumberGroupSeparator = separator; culture.NumberFormat.NumberGroupSizes = sizes; return culture; } public class InvariantTests : TestFixture { public void GroupsByThreesWithCommasAndAPlainMinus() { CheckEqual(",", NumberFormat.Invariant.GroupSeparator); CheckEqual(3, NumberFormat.Invariant.PrimaryGroupSize); CheckEqual(3, NumberFormat.Invariant.SecondaryGroupSize); CheckEqual("-", NumberFormat.Invariant.MinusSign); } public void UsesAPeriodAndTheWordsNaNAndInfinity() { CheckEqual(".", NumberFormat.Invariant.DecimalSeparator); CheckEqual("NaN", NumberFormat.Invariant.NotANumberSymbol); CheckEqual("Infinity", NumberFormat.Invariant.InfinitySymbol); } public void UsesTheEnglishShortNotation() { CheckTrue(ReferenceEquals(ShortNotation.English, NumberFormat.Invariant.ShortNotation)); } public void UsesALowercaseEForTheExponent() { CheckEqual("e", NumberFormat.Invariant.ExponentSymbol); } } public class CtorTests : TestFixture { public void KeepsEveryValue() { var format = new NumberFormat(" ", 3, 2, "~", ",", "?", "inf", "e", ShortNotation.English); CheckEqual(" ", format.GroupSeparator); CheckEqual(3, format.PrimaryGroupSize); CheckEqual(2, format.SecondaryGroupSize); CheckEqual("~", format.MinusSign); CheckEqual(",", format.DecimalSeparator); CheckEqual("?", format.NotANumberSymbol); CheckEqual("inf", format.InfinitySymbol); } public void KeepsTheShortNotation() { var notation = ShortNotation.FromGroups(new[] { "k" }, "", 3); CheckTrue(ReferenceEquals(notation, new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", notation).ShortNotation)); } public void ANullShortNotation_Throws() { CheckThrow(typeof(ArgumentNullException)); new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", null); } public void MaxShortLength_IsNeverBelowTheScientificLength() { CheckEqual(NumberFormat.Invariant.MaxScientificLength, NumberFormat.Invariant.MaxShortLength); } public void MaxShortLength_CoversTheLongestWrittenOutValue() { var format = new NumberFormat(",", 3, 3, "", "", "NaN", "Infinity", "", ShortNotation.English); CheckEqual(1 + 5 + 3 + 15, format.MaxShortLength); } public void MaxShortLength_GrowsWithTheLongestSuffix() { var notation = ShortNotation.FromGroups(new[] { "K", "AVERYLONGSUFFIXINDEED" }, "", 3); var format = new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", notation); CheckEqual(1 + 15 + 1 + 21, format.MaxShortLength); } public void KeepsTheExponentSymbol() { CheckEqual("x10^", new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "x10^", ShortNotation.English).ExponentSymbol); } public void MaxScientificLength_CoversTheDigitsSeparatorsSignsAndExponent() { CheckEqual(1 + 1 + 1 + 14 + 1 + 1 + 3, NumberFormat.Invariant.MaxScientificLength); CheckEqual(2 * 5 + 1 + 5 + 14 + 3 + 3, new NumberFormat(",", 3, 3, "MINUS", "", "NaN", "Infinity", "EXP", ShortNotation.English).MaxScientificLength); } public void MaxScientificLength_IsNeverBelowTheSymbolLength() { var format = new NumberFormat(",", 3, 3, "-", ".", new string('N', 100), "Infinity", "e", ShortNotation.English); CheckEqual(100, format.MaxScientificLength); } public void ANullExponentSymbol_Throws() { CheckThrow(typeof(ArgumentNullException)); new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", null, ShortNotation.English); } public void NoPrimaryGroup_MeansNoGroupingAtAll() { CheckEqual(0, Grouping(",", 0, 2, "-").SecondaryGroupSize); } public void MaxCountLength_CoversTheDigitsSeparatorsAndSign() { CheckEqual(19 + 6 + 1, NumberFormat.Invariant.MaxCountLength); CheckEqual(19 + 18 * 3 + 5, Grouping("<->", 1, 1, "MINUS").MaxCountLength); } public void NoGrouping_HasAMaxCountLengthOfDigitsAndSign() { CheckEqual(19 + 1, Grouping(",", 0, 0, "-").MaxCountLength); } public void MaxFixedLength_CoversTwentyNineDigitsTheSeparatorsTheSignAndNineDecimals() { CheckEqual(1 + 29 + 9 + 1 + 9, NumberFormat.Invariant.MaxFixedLength); var longSeparator = new NumberFormat(",", 3, 3, "-", "", "NaN", "Infinity", "e", ShortNotation.English); CheckEqual(1 + 29 + 9 + 5 + 9, longSeparator.MaxFixedLength); } public void MaxFixedLength_IsNeverBelowTheSymbolLength() { var format = new NumberFormat(",", 3, 3, "-", ".", new string('N', 100), "Infinity", "e", ShortNotation.English); CheckEqual(100, format.MaxFixedLength); } public void MaxSymbolLength_IsTheLongerOfNaNAndMinusInfinity() { CheckEqual(9, NumberFormat.Invariant.MaxSymbolLength); CheckEqual(10, new NumberFormat(",", 3, 3, "-", ".", "NotANumber", "inf", "e", ShortNotation.English).MaxSymbolLength); } public void ANullSeparator_Throws() { CheckThrow(typeof(ArgumentNullException)); new NumberFormat(null, 3, 3, "-", ".", "NaN", "Infinity", "e", ShortNotation.English); } public void ANullMinusSign_Throws() { CheckThrow(typeof(ArgumentNullException)); new NumberFormat(",", 3, 3, null, ".", "NaN", "Infinity", "e", ShortNotation.English); } public void ANullDecimalSeparator_Throws() { CheckThrow(typeof(ArgumentNullException)); new NumberFormat(",", 3, 3, "-", null, "NaN", "Infinity", "e", ShortNotation.English); } public void ANullNotANumberSymbol_Throws() { CheckThrow(typeof(ArgumentNullException)); new NumberFormat(",", 3, 3, "-", ".", null, "Infinity", "e", ShortNotation.English); } public void ANullInfinitySymbol_Throws() { CheckThrow(typeof(ArgumentNullException)); new NumberFormat(",", 3, 3, "-", ".", "NaN", null, "e", ShortNotation.English); } public void ANegativePrimaryGroupSize_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); Grouping(",", -1, 3, "-"); } public void ANegativeSecondaryGroupSize_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); Grouping(",", 3, -1, "-"); } } public class FromCultureTests : TestFixture { public void InvariantCulture_GroupsByThreesWithCommas() { NumberFormat format = NumberFormat.FromCulture(CultureInfo.InvariantCulture); CheckEqual("1,234,567", CountOf(format, 1234567)); } public void GermanCulture_GroupsWithPeriods() { CheckEqual("1.234.567", CountOf(NumberFormat.FromCulture(new CultureInfo("de-DE")), 1234567)); } public void IndianCulture_GroupsByThreeThenTwo() { CheckEqual("12,34,567", CountOf(NumberFormat.FromCulture(new CultureInfo("en-IN")), 1234567)); } public void ACulturesMinusSign_IsUsed() { var culture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); culture.NumberFormat.NegativeSign = "~"; CheckEqual("~5", CountOf(NumberFormat.FromCulture(culture), -5)); } public void AMultiCharacterSeparator_IsUsedWhole() { CheckEqual("1<>234", CountOf(NumberFormat.FromCulture(CultureWithGroupSizes("<>", 3)), 1234)); } public void ASingleSize_RepeatsForEveryGroup() { CheckEqual("1,234,567", CountOf(NumberFormat.FromCulture(CultureWithGroupSizes(",", 3)), 1234567)); } public void ASizeFollowedByZero_MakesOnlyTheFirstGroup() { CheckEqual("1234,567", CountOf(NumberFormat.FromCulture(CultureWithGroupSizes(",", 3, 0)), 1234567)); } public void NoSizes_MeansNoGrouping() { CheckEqual("1234567", CountOf(NumberFormat.FromCulture(CultureWithGroupSizes(",")), 1234567)); } public void AZeroFirstSize_MeansNoGrouping() { CheckEqual("1234567", CountOf(NumberFormat.FromCulture(CultureWithGroupSizes(",", 0)), 1234567)); } public void ACulturesDecimalSeparator_IsUsed() { NumberFormat format = NumberFormat.FromCulture(new CultureInfo("de-DE")); CheckEqual(",", format.DecimalSeparator); CheckEqual("1.234,50", FixedOf(format, 1234.5, 2)); } public void ACulturesNaNAndInfinitySymbols_AreUsed() { var culture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); culture.NumberFormat.NaNSymbol = "nan!"; culture.NumberFormat.PositiveInfinitySymbol = "inf!"; NumberFormat format = NumberFormat.FromCulture(culture); CheckEqual("nan!", format.NotANumberSymbol); CheckEqual("inf!", format.InfinitySymbol); } public void AnyCulture_UsesTheEnglishShortNotation() { CheckTrue(ReferenceEquals(ShortNotation.English, NumberFormat.FromCulture(new CultureInfo("de-DE")).ShortNotation)); } public void AnyCulture_UsesALowercaseEForTheExponent() { CheckEqual("e", NumberFormat.FromCulture(new CultureInfo("de-DE")).ExponentSymbol); } public void ANullCulture_Throws() { CheckThrow(typeof(ArgumentNullException)); NumberFormat.FromCulture(null); } } public class DigitCountTests : TestFixture { public void Zero_HasOneDigit() { CheckEqual(1, NumberFormat.DigitCount(0)); } public void TheEdgesOfEachLength_AreCounted() { CheckEqual(1, NumberFormat.DigitCount(9)); CheckEqual(2, NumberFormat.DigitCount(10)); CheckEqual(2, NumberFormat.DigitCount(99)); CheckEqual(3, NumberFormat.DigitCount(100)); } public void TheLargestMagnitude_HasTwentyDigits() { CheckEqual(20, NumberFormat.DigitCount(ulong.MaxValue)); } } public class MagnitudeOfTests : TestFixture { public void Positive_IsItself() { CheckEqual(42UL, NumberFormat.MagnitudeOf(42)); } public void Negative_DropsTheSign() { CheckEqual(42UL, NumberFormat.MagnitudeOf(-42)); } public void MinValue_IsOneMoreThanMaxValue() { CheckEqual((ulong)long.MaxValue + 1, NumberFormat.MagnitudeOf(long.MinValue)); } } public class WriteNinesTests : TestFixture { private const int MostNines = 19; public static string NinesOf(NumberFormat format, int count, int size = 32) { var buffer = new char[size]; int end = format.WriteNines(count, buffer, 0); return new string(buffer, 0, end); } public void OneNine_IsOneDigit() { CheckEqual("9", NinesOf(NumberFormat.Invariant, 1)); } public void ManyNines_HaveNoSeparators() { CheckEqual("999999", NinesOf(NumberFormat.Invariant, 6)); } public void TheMostNines_AreWritten() { CheckEqual(new string('9', MostNines), NinesOf(NumberFormat.Invariant, MostNines)); } public void ALanguageWithOtherDigits_WritesItsOwnNine() { NumberFormat arabic = NumberFormat.For("ar-EG"); CheckEqual(new string((char)(arabic.ZeroDigit + 9), 3), NinesOf(arabic, 3)); } public void ReturnsThePositionAfterTheRun() { var buffer = new char[8]; CheckEqual(5, NumberFormat.Invariant.WriteNines(3, buffer, 2)); } public void NoNines_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); NinesOf(NumberFormat.Invariant, 0); } public void MoreNinesThanALongHolds_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); NinesOf(NumberFormat.Invariant, MostNines + 1); } public void ARunThatDoesNotFit_Throws() { CheckThrow(typeof(ArgumentException)); NinesOf(NumberFormat.Invariant, 5, size: 4); } } public class WriteCountTests : TestFixture { public void Zero_IsOneDigit() { CheckEqual("0", CountOf(NumberFormat.Invariant, 0)); } public void JustBelowAGroup_HasNoSeparator() { CheckEqual("999", CountOf(NumberFormat.Invariant, 999)); } public void ExactlyOneGroup_GainsASeparator() { CheckEqual("1,000", CountOf(NumberFormat.Invariant, 1000)); } public void ExactlyTheGroupSize_HasNoLeadingSeparator() { CheckEqual("100,000", CountOf(NumberFormat.Invariant, 100000)); CheckEqual("1,000,000", CountOf(NumberFormat.Invariant, 1000000)); } public void Negative_GetsTheMinusSignBeforeTheGroups() { CheckEqual("-1,234", CountOf(NumberFormat.Invariant, -1234)); CheckEqual("-999", CountOf(NumberFormat.Invariant, -999)); } public void Extremes_AreWrittenInFull() { CheckEqual("9,223,372,036,854,775,807", CountOf(NumberFormat.Invariant, long.MaxValue)); CheckEqual("-9,223,372,036,854,775,808", CountOf(NumberFormat.Invariant, long.MinValue)); } public void ASecondarySize_AppliesAfterTheFirstGroup() { var indian = Grouping(",", 3, 2, "-"); CheckEqual("1,000", CountOf(indian, 1000)); CheckEqual("10,000", CountOf(indian, 10000)); CheckEqual("1,00,000", CountOf(indian, 100000)); CheckEqual("1,23,45,67,890", CountOf(indian, 1234567890)); } public void ASecondarySizeOfZero_MakesOnlyTheFirstGroup() { CheckEqual("12345,678", CountOf(Grouping(",", 3, 0, "-"), 12345678)); } public void APrimarySizeOfZero_MakesNoGroups() { CheckEqual("12345678", CountOf(Grouping(",", 0, 3, "-"), 12345678)); } public void GroupsOfOne_SeparateEveryDigit() { CheckEqual("1-2-3", CountOf(Grouping("-", 1, 1, "~"), 123)); } public void AnEmptySeparator_JoinsTheGroups() { CheckEqual("1234", CountOf(Grouping("", 3, 3, "-"), 1234)); } public void AnEmptyMinusSign_WritesNone() { CheckEqual("1,234", CountOf(Grouping(",", 3, 3, ""), -1234)); } public void LongSeparatorsAndMinusSigns_AreWrittenWhole() { var format = Grouping("<->", 3, 3, "MINUS "); CheckEqual("MINUS 12<->345", CountOf(format, -12345)); } public void WritesAtThePositionAndReturnsTheEnd() { var buffer = new char[20]; for (int i = 0; i < buffer.Length; ++i) { buffer[i] = '#'; } int end = NumberFormat.Invariant.WriteCount(-1234, buffer, 3); CheckEqual(9, end); CheckEqual("###-1,234###########", new string(buffer)); } } public class TryRoundFixedTests : TestFixture { public void RoundsHalfAwayFromZero() { CheckTrue(NumberFormat.TryRoundFixed(2.5, 0, out decimal rounded)); CheckEqual(3m, rounded); CheckTrue(NumberFormat.TryRoundFixed(-2.5, 0, out rounded)); CheckEqual(-3m, rounded); } public void ReadsTheValueAsItsFifteenSignificantDigits() { CheckTrue(NumberFormat.TryRoundFixed(1.005, 2, out decimal rounded)); CheckEqual(1.01m, rounded); } public void NaN_CannotBeRounded() { CheckFalse(NumberFormat.TryRoundFixed(double.NaN, 2, out _)); } public void Infinities_CannotBeRounded() { CheckFalse(NumberFormat.TryRoundFixed(double.PositiveInfinity, 2, out _)); CheckFalse(NumberFormat.TryRoundFixed(double.NegativeInfinity, 2, out _)); } public void AValueBeyondWhatTheArithmeticHolds_CannotBeRounded() { CheckFalse(NumberFormat.TryRoundFixed(7.9e28, 2, out _)); CheckFalse(NumberFormat.TryRoundFixed(-1e30, 2, out _)); CheckTrue(NumberFormat.TryRoundFixed(7.8e28, 2, out _)); } public void ADecimalCountOutOfRange_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); NumberFormat.TryRoundFixed(1, 10, out _); } public void ANegativeDecimalCount_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); NumberFormat.TryRoundFixed(1, -1, out _); } } public class WriteFixedTests : TestFixture { public void Decimals_FollowTheDecimalSeparator() { CheckEqual("12.34", FixedOf(NumberFormat.Invariant, 12.34, 2)); } public void ZeroDecimals_WriteNoSeparator() { CheckEqual("1,234", FixedOf(NumberFormat.Invariant, 1234, 0)); } public void TheWholePart_IsGrouped() { CheckEqual("1,234,567.89", FixedOf(NumberFormat.Invariant, 1234567.89, 2)); CheckEqual("12,34,567.89", FixedOf(Grouping(",", 3, 2, "-"), 1234567.89, 2)); } public void TheDecimals_AreNeverGrouped() { CheckEqual("0.123456", FixedOf(NumberFormat.Invariant, 0.123456, 6)); } public void AFractionOnly_HasAZeroWholePart() { CheckEqual("0.05", FixedOf(NumberFormat.Invariant, 0.05, 2)); } public void LeadingZerosOfTheFraction_AreKept() { CheckEqual("1.005", FixedOf(NumberFormat.Invariant, 1.005, 3)); } public void TrailingZerosOfTheFraction_AreKept() { CheckEqual("12.50", FixedOf(NumberFormat.Invariant, 12.5, 2)); } public void Zero_IsZeroWithItsDecimals() { CheckEqual("0.00", FixedOf(NumberFormat.Invariant, 0, 2)); } public void Negative_GetsTheMinusSign() { CheckEqual("-1,234.50", FixedOf(NumberFormat.Invariant, -1234.5, 2)); CheckEqual("-0.05", FixedOf(NumberFormat.Invariant, -0.05, 2)); } public void AValueThatRoundsToZero_HasNoMinusSign() { CheckEqual("0.00", FixedOf(NumberFormat.Invariant, -0.001, 2)); CheckEqual("0.00", FixedOf(NumberFormat.Invariant, -0.0, 2)); } public void RoundsHalfAwayFromZero() { CheckEqual("3", FixedOf(NumberFormat.Invariant, 2.5, 0)); CheckEqual("-3", FixedOf(NumberFormat.Invariant, -2.5, 0)); CheckEqual("1.5", FixedOf(NumberFormat.Invariant, 1.45, 1)); CheckEqual("-1.5", FixedOf(NumberFormat.Invariant, -1.45, 1)); } public void ReadsTheValueAsItsFifteenSignificantDigits() { CheckEqual("1.01", FixedOf(NumberFormat.Invariant, 1.005, 2)); CheckEqual("0.3", FixedOf(NumberFormat.Invariant, 0.1 + 0.2, 1)); } public void RoundingUp_CarriesIntoTheWholePart() { CheckEqual("1,000.00", FixedOf(NumberFormat.Invariant, 999.999, 2)); } public void AValueTooSmallForADecimal_IsZero() { CheckEqual("0.00", FixedOf(NumberFormat.Invariant, 1e-30, 2)); } public void TheDecimalSeparatorAndMinusSign_AreTheFormats() { var format = new NumberFormat(".", 3, 3, "~", ",", "NaN", "Infinity", "e", ShortNotation.English); CheckEqual("~1.234,50", FixedOf(format, -1234.5, 2)); } public void ALongDecimalSeparator_IsWrittenWhole() { var format = new NumberFormat(",", 3, 3, "-", "", "NaN", "Infinity", "e", ShortNotation.English); CheckEqual("150", FixedOf(format, 1.5, 2)); } public void NineDecimals_AreAllWritten() { CheckEqual("0.000000005", FixedOf(NumberFormat.Invariant, 0.000000005, 9)); } public void ALargeValueWithManyDecimals_IsNotLimited() { CheckEqual("10,000,000,000.000000000", FixedOf(NumberFormat.Invariant, 1e10, 9)); } public void AWholePartPastAUlong_IsWrittenInFull() { CheckEqual("10,000,000,000,000,000,000,000,000.00", FixedOf(NumberFormat.Invariant, 1e25, 2)); CheckEqual("-12,345,678,901,234,500,000,000,000.00", FixedOf(NumberFormat.Invariant, -1.23456789012345e25, 2)); } public void AWholePartAtTheQuintillionBoundary_KeepsItsZeros() { CheckEqual("1,000,000,000,000,000,000", FixedOf(NumberFormat.Invariant, 1e18, 0)); CheckEqual("999,999,999,999,999,000", FixedOf(NumberFormat.Invariant, 9.99999999999999e17, 0)); } public void TheLargestValues_AreWrittenInFull() { CheckEqual("78,000,000,000,000,000,000,000,000,000.000000000", FixedOf(NumberFormat.Invariant, 7.8e28, 9)); } public void AValueTooLargeForTheArithmetic_IsAnInfinity() { CheckEqual("Infinity", FixedOf(NumberFormat.Invariant, 7.9e28, 2)); CheckEqual("-Infinity", FixedOf(NumberFormat.Invariant, -1e30, 2)); CheckEqual("Infinity", FixedOf(NumberFormat.Invariant, double.MaxValue, 2)); } public void Infinities_AreTheFormatsSymbol() { CheckEqual("Infinity", FixedOf(NumberFormat.Invariant, double.PositiveInfinity, 2)); CheckEqual("-Infinity", FixedOf(NumberFormat.Invariant, double.NegativeInfinity, 2)); } public void NaN_IsTheFormatsSymbol() { CheckEqual("NaN", FixedOf(NumberFormat.Invariant, double.NaN, 2)); } public void TheLongestOutput_FitsMaxFixedLength() { var format = new NumberFormat("<->", 1, 1, "MINUS", "", "NaN", "Infinity", "e", ShortNotation.English); var buffer = new char[format.MaxFixedLength]; int end = format.WriteFixed(-7.8e28, 9, buffer, 0); CheckEqual("MINUS7<->8<->0<->0<->0<->0<->0<->0<->0<->0<->0<->0<->0<->0<->0<->0<->0<->0<->0<->0" + "<->0<->0<->0<->0<->0<->0<->0<->0<->0000000000", new string(buffer, 0, end)); } public void ADecimalCountOutOfRange_Throws() { var buffer = new char[100]; CheckThrow(typeof(ArgumentOutOfRangeException)); NumberFormat.Invariant.WriteFixed(1, 10, buffer, 0); } public void ANegativeDecimalCount_Throws() { var buffer = new char[100]; CheckThrow(typeof(ArgumentOutOfRangeException)); NumberFormat.Invariant.WriteFixed(1, -1, buffer, 0); } public void WritesAtThePositionAndReturnsTheEnd() { var buffer = new char[10]; for (int i = 0; i < buffer.Length; ++i) { buffer[i] = '#'; } int end = NumberFormat.Invariant.WriteFixed(1.25, 2, buffer, 2); CheckEqual(6, end); CheckEqual("##1.25####", new string(buffer)); } } public class WriteScientificTests : TestFixture { public void AMantissaOfTheDigitsAskedFor_FollowsTheExponent() { CheckEqual("1.23e3", ScientificOf(NumberFormat.Invariant, 1234.5, 3)); CheckEqual("1.2345e3", ScientificOf(NumberFormat.Invariant, 1234.5, 5)); } public void OneDigit_HasNoDecimalSeparator() { CheckEqual("1e0", ScientificOf(NumberFormat.Invariant, 1, 1)); CheckEqual("5e7", ScientificOf(NumberFormat.Invariant, 5e7, 1)); } public void Zero_IsAZeroMantissaAndExponent() { CheckEqual("0.00e0", ScientificOf(NumberFormat.Invariant, 0, 3)); CheckEqual("0e0", ScientificOf(NumberFormat.Invariant, -0.0, 1)); } public void TrailingZerosOfTheMantissa_AreKept() { CheckEqual("1.20e5", ScientificOf(NumberFormat.Invariant, 120000, 3)); CheckEqual("1.00000000000000e-1", ScientificOf(NumberFormat.Invariant, 0.1, 15)); } public void AllFifteenDigits_AreWritten() { CheckEqual("1.23456789000000e8", ScientificOf(NumberFormat.Invariant, 123456789, 15)); } public void Negative_GetsTheMinusSignBeforeTheMantissa() { CheckEqual("-1.5e-7", ScientificOf(NumberFormat.Invariant, -1.5e-7, 2)); CheckEqual("-1.50e3", ScientificOf(NumberFormat.Invariant, -1500, 3)); } public void ANegativeExponent_GetsTheMinusSign() { CheckEqual("1.23e-5", ScientificOf(NumberFormat.Invariant, 0.0000123, 3)); } public void RoundsHalfAwayFromZero() { CheckEqual("1.235e3", ScientificOf(NumberFormat.Invariant, 1234.5, 4)); CheckEqual("3e0", ScientificOf(NumberFormat.Invariant, 2.5, 1)); CheckEqual("-3e0", ScientificOf(NumberFormat.Invariant, -2.5, 1)); CheckEqual("1.01e0", ScientificOf(NumberFormat.Invariant, 1.005, 3)); } public void RoundingUp_CarriesIntoTheExponent() { CheckEqual("1.00e1", ScientificOf(NumberFormat.Invariant, 9.995, 3)); CheckEqual("1.00e6", ScientificOf(NumberFormat.Invariant, 999999.9, 3)); CheckEqual("1.00e0", ScientificOf(NumberFormat.Invariant, 0.9999, 3)); CheckEqual("1e-4", ScientificOf(NumberFormat.Invariant, 0.00009999, 1)); } public void ExactPowersOfTen_HaveAMantissaOfOne() { for (int power = -20; power <= 20; ++power) { double value = double.Parse("1e" + power, CultureInfo.InvariantCulture); CheckEqual("1.00e" + (power < 0 ? "-" : "") + Math.Abs(power), ScientificOf(NumberFormat.Invariant, value, 3)); } } public void TheLargestDoubles_AreWritten() { CheckEqual("1.00e308", ScientificOf(NumberFormat.Invariant, 1e308, 3)); CheckEqual("1.80e308", ScientificOf(NumberFormat.Invariant, double.MaxValue, 3)); CheckEqual("-1.80e308", ScientificOf(NumberFormat.Invariant, -double.MaxValue, 3)); } public void TheSmallestDoubles_AreWritten() { CheckEqual("4.94e-324", ScientificOf(NumberFormat.Invariant, double.Epsilon, 3)); CheckEqual("2.23e-308", ScientificOf(NumberFormat.Invariant, 2.2250738585072014e-308, 3)); CheckEqual("1.00e-310", ScientificOf(NumberFormat.Invariant, 1e-310, 3)); } public void TheFormatsSeparatorsAndSymbols_AreUsed() { var format = new NumberFormat(".", 3, 3, "~", ",", "NaN", "Infinity", " x10^", ShortNotation.English); CheckEqual("~1,23 x10^~3", ScientificOf(format, -0.00123, 3)); CheckEqual("4,5 x10^6", ScientificOf(format, 4500000, 2)); } public void NaN_IsTheFormatsSymbol() { CheckEqual("NaN", ScientificOf(NumberFormat.Invariant, double.NaN, 3)); } public void Infinities_AreTheFormatsSymbol() { CheckEqual("Infinity", ScientificOf(NumberFormat.Invariant, double.PositiveInfinity, 3)); CheckEqual("-Infinity", ScientificOf(NumberFormat.Invariant, double.NegativeInfinity, 3)); } public void TheLongestOutput_FillsMaxScientificLengthExactly() { var format = new NumberFormat(",", 3, 3, "MINUS", "", "NaN", "Infinity", "EXP", ShortNotation.English); var buffer = new char[format.MaxScientificLength]; int end = format.WriteScientific(-1.23456789012345e-300, 15, buffer, 0); CheckEqual(format.MaxScientificLength, end); CheckEqual("MINUS123456789012345EXPMINUS300", new string(buffer, 0, end)); } public void ZeroDigits_Throw() { var buffer = new char[100]; CheckThrow(typeof(ArgumentOutOfRangeException)); NumberFormat.Invariant.WriteScientific(1, 0, buffer, 0); } public void SixteenDigits_Throw() { var buffer = new char[100]; CheckThrow(typeof(ArgumentOutOfRangeException)); NumberFormat.Invariant.WriteScientific(1, 16, buffer, 0); } public void WritesAtThePositionAndReturnsTheEnd() { var buffer = new char[12]; for (int i = 0; i < buffer.Length; ++i) { buffer[i] = '#'; } int end = NumberFormat.Invariant.WriteScientific(1250, 3, buffer, 2); CheckEqual(8, end); CheckEqual("##1.25e3####", new string(buffer)); } } public class WriteShortExponentTests : TestFixture { public void BelowAThousand_HasNoSuffix() { CheckEqual("1.00", ShortOf(NumberFormat.Invariant, 1, 3)); CheckEqual("12.3", ShortOf(NumberFormat.Invariant, 12.3456, 3)); CheckEqual("123", ShortOf(NumberFormat.Invariant, 123.456, 3)); CheckEqual("999", ShortOf(NumberFormat.Invariant, 999, 3)); } public void Zero_IsZeroWithItsDigits() { CheckEqual("0.00", ShortOf(NumberFormat.Invariant, 0, 3)); CheckEqual("0", ShortOf(NumberFormat.Invariant, 0, 1)); CheckEqual("0", ShortOf(NumberFormat.Invariant, -0.0, 1)); } public void EachNamedSuffix_StartsAtItsPower() { CheckEqual("1.00K", ShortOf(NumberFormat.Invariant, 1000, 3)); CheckEqual("1.00M", ShortOf(NumberFormat.Invariant, 1e6, 3)); CheckEqual("1.00B", ShortOf(NumberFormat.Invariant, 1e9, 3)); CheckEqual("1.00T", ShortOf(NumberFormat.Invariant, 1e12, 3)); } public void TheGeneratedSuffixes_FollowTheNamedOnes() { CheckEqual("1.00aa", ShortOf(NumberFormat.Invariant, 1e15, 3)); CheckEqual("1.00ab", ShortOf(NumberFormat.Invariant, 1e18, 3)); CheckEqual("1.00ag", ShortOf(NumberFormat.Invariant, 1e33, 3)); CheckEqual("1.00az", ShortOf(NumberFormat.Invariant, 1e90, 3)); CheckEqual("1.00ba", ShortOf(NumberFormat.Invariant, 1e93, 3)); } public void TheLargestDouble_IsTwoLetters() { CheckEqual("100dt", ShortOf(NumberFormat.Invariant, 1e308, 3)); CheckEqual("180dt", ShortOf(NumberFormat.Invariant, double.MaxValue, 3)); } public void TheMantissa_ShiftsWithinTheGroup() { CheckEqual("1.23K", ShortOf(NumberFormat.Invariant, 1234, 3)); CheckEqual("12.3K", ShortOf(NumberFormat.Invariant, 12345, 3)); CheckEqual("123K", ShortOf(NumberFormat.Invariant, 123456, 3)); CheckEqual("1.23M", ShortOf(NumberFormat.Invariant, 1234567, 3)); CheckEqual("1.50M", ShortOf(NumberFormat.Invariant, 1.5e6, 3)); } public void TheWholePart_IsNeverCutShort() { CheckEqual("123K", ShortOf(NumberFormat.Invariant, 123456, 2)); CheckEqual("123K", ShortOf(NumberFormat.Invariant, 123456, 1)); CheckEqual("12K", ShortOf(NumberFormat.Invariant, 12345, 1)); CheckEqual("2K", ShortOf(NumberFormat.Invariant, 1500, 1)); } public void RoundingUp_CarriesIntoTheNextSuffix() { CheckEqual("1.00K", ShortOf(NumberFormat.Invariant, 999.5, 3)); CheckEqual("1.00M", ShortOf(NumberFormat.Invariant, 999500, 3)); CheckEqual("1.00aa", ShortOf(NumberFormat.Invariant, 999.9e12, 3)); CheckEqual("1.00ba", ShortOf(NumberFormat.Invariant, 9.9999e92, 3)); } public void RoundingUp_RecomputesTheDigitsAfterTheCarry() { CheckEqual("1.0K", ShortOf(NumberFormat.Invariant, 999.6, 2)); CheckEqual("100", ShortOf(NumberFormat.Invariant, 99.96, 2)); CheckEqual("1K", ShortOf(NumberFormat.Invariant, 999.6, 1)); } public void RoundsHalfAwayFromZero() { CheckEqual("13", ShortOf(NumberFormat.Invariant, 12.5, 2)); CheckEqual("-13", ShortOf(NumberFormat.Invariant, -12.5, 2)); CheckEqual("1.24K", ShortOf(NumberFormat.Invariant, 1235, 3)); } public void Negative_GetsTheMinusSign() { CheckEqual("-1.23K", ShortOf(NumberFormat.Invariant, -1234, 3)); CheckEqual("-1.00K", ShortOf(NumberFormat.Invariant, -999.5, 3)); CheckEqual("-12.3", ShortOf(NumberFormat.Invariant, -12.3456, 3)); } public void BelowOne_IsWrittenOutWithItsSignificantDigits() { CheckEqual("0.250", ShortOf(NumberFormat.Invariant, 0.25, 3)); CheckEqual("0.0123", ShortOf(NumberFormat.Invariant, 0.0123, 3)); CheckEqual("0.000123", ShortOf(NumberFormat.Invariant, 0.00012345, 3)); CheckEqual("0.0005", ShortOf(NumberFormat.Invariant, 0.00049, 1)); CheckEqual("-0.250", ShortOf(NumberFormat.Invariant, -0.25, 3)); } public void TheSmallestWrittenOutValue_IsOneTenThousandth() { CheckEqual("0.000100", ShortOf(NumberFormat.Invariant, 0.0001, 3)); CheckEqual("0.0001", ShortOf(NumberFormat.Invariant, 0.0001, 1)); } public void BelowOneTenThousandth_IsScientific() { CheckEqual("1.00e-5", ShortOf(NumberFormat.Invariant, 0.00001, 3)); CheckEqual("-1.5e-7", ShortOf(NumberFormat.Invariant, -1.5e-7, 2)); CheckEqual("4.94e-324", ShortOf(NumberFormat.Invariant, double.Epsilon, 3)); } public void RoundingUp_CarriesAcrossTheEdgeOfTheWrittenOutRange() { CheckEqual("0.000100", ShortOf(NumberFormat.Invariant, 0.00009999, 3)); CheckEqual("1.00", ShortOf(NumberFormat.Invariant, 0.99996, 3)); } public void TheFormatsSeparatorsAndSymbols_AreUsed() { var format = new NumberFormat(".", 3, 3, "~", ",", "NaN", "Infinity", "E", ShortNotation.English); CheckEqual("~1,23K", ShortOf(format, -1234, 3)); CheckEqual("0,250", ShortOf(format, 0.25, 3)); CheckEqual("1,00E~5", ShortOf(format, 0.00001, 3)); } public void ACustomNotationsStepAndSuffixes_AreUsed() { var notation = ShortNotation.FromGroups(new[] { "w", "y", "z" }, "", 4); var format = new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", notation); CheckEqual("1234", ShortOf(format, 1234, 3)); CheckEqual("1.23w", ShortOf(format, 12345, 3)); CheckEqual("12.3w", ShortOf(format, 123456, 3)); CheckEqual("123w", ShortOf(format, 1234567, 3)); CheckEqual("1235w", ShortOf(format, 12345678, 3)); CheckEqual("1.23y", ShortOf(format, 123456789, 3)); CheckEqual("1.00z", ShortOf(format, 1e12, 3)); } public void ASuffixlessStep_NeverCutsTheWholePartShort() { var notation = ShortNotation.FromGroups(new[] { "w" }, "", 4); var format = new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", notation); CheckEqual("1235", ShortOf(format, 1234.5, 2)); } public void PastTheLastSuffix_IsScientific() { var notation = ShortNotation.FromGroups(new[] { "w", "y", "z" }, "", 4); var format = new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", notation); CheckEqual("1.00e16", ShortOf(format, 1e16, 3)); CheckEqual("1.23e20", ShortOf(format, 1.2345e20, 3)); CheckEqual("-1.00e16", ShortOf(format, -1e16, 3)); } public void RoundingUp_CarriesPastTheLastSuffixIntoScientific() { var notation = ShortNotation.FromGroups(new[] { "w", "y", "z" }, "", 4); var format = new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", notation); CheckEqual("9996z", ShortOf(format, 9.996e15, 3)); CheckEqual("1.00e16", ShortOf(format, 9.9996e15, 3)); } public void FewLetters_MakeLongSuffixes() { var notation = ShortNotation.FromGroups(new[] { "K" }, "ab", 3); var format = new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", notation); CheckEqual("1.00ba", ShortOf(format, 1e12, 3)); CheckEqual("1.00bb", ShortOf(format, 1e15, 3)); CheckEqual("1.00aaa", ShortOf(format, 1e18, 3)); } public void NaN_IsTheFormatsSymbol() { CheckEqual("NaN", ShortOf(NumberFormat.Invariant, double.NaN, 3)); } public void Infinities_AreTheFormatsSymbol() { CheckEqual("Infinity", ShortOf(NumberFormat.Invariant, double.PositiveInfinity, 3)); CheckEqual("-Infinity", ShortOf(NumberFormat.Invariant, double.NegativeInfinity, 3)); } public void FifteenDigits_AreAllWritten() { CheckEqual("1.23456789012345K", ShortOf(NumberFormat.Invariant, 1234.56789012345, 15)); CheckEqual("123.456789012345K", ShortOf(NumberFormat.Invariant, 123456.789012345, 15)); } public void TheLongestOutput_FitsMaxShortLength() { var format = new NumberFormat(",", 3, 3, "MINUS", "", "NaN", "Infinity", "EXP", ShortNotation.English); var buffer = new char[format.MaxShortLength]; int end = format.WriteShortExponent(-1.23456789012345e308, 15, buffer, 0); CheckEqual("MINUS123456789012345dt", new string(buffer, 0, end)); CheckTrue(end <= format.MaxShortLength); } public void TheLongestWrittenOutValue_FitsMaxShortLength() { var format = new NumberFormat(",", 3, 3, "MINUS", "", "NaN", "Infinity", "EXP", ShortNotation.English); var buffer = new char[format.MaxShortLength]; int end = format.WriteShortExponent(-0.000123456789012345, 15, buffer, 0); CheckEqual("MINUS0000123456789012345", new string(buffer, 0, end)); CheckTrue(end <= format.MaxShortLength); } public void ZeroDigits_Throw() { var buffer = new char[100]; CheckThrow(typeof(ArgumentOutOfRangeException)); NumberFormat.Invariant.WriteShortExponent(1, 0, buffer, 0); } public void SixteenDigits_Throw() { var buffer = new char[100]; CheckThrow(typeof(ArgumentOutOfRangeException)); NumberFormat.Invariant.WriteShortExponent(1, 16, buffer, 0); } public void WritesAtThePositionAndReturnsTheEnd() { var buffer = new char[10]; for (int i = 0; i < buffer.Length; ++i) { buffer[i] = '#'; } int end = NumberFormat.Invariant.WriteShortExponent(1250, 3, buffer, 2); CheckEqual(7, end); CheckEqual("##1.25K###", new string(buffer)); } } public class WriteNotANumberTests : TestFixture { public void WritesTheSymbolAtThePosition() { var buffer = new char[6]; int end = NumberFormat.Invariant.WriteNotANumber(buffer, 2); CheckEqual(5, end); CheckEqual("NaN", new string(buffer, 2, 3)); } } public class WriteInfinityTests : TestFixture { public void Positive_WritesTheSymbol() { var buffer = new char[10]; int end = NumberFormat.Invariant.WriteInfinity(negative: false, buffer, 0); CheckEqual("Infinity", new string(buffer, 0, end)); } public void Negative_WritesTheMinusSignFirst() { var buffer = new char[10]; int end = NumberFormat.Invariant.WriteInfinity(negative: true, buffer, 0); CheckEqual("-Infinity", new string(buffer, 0, end)); } } public class PercentAndTimeCtorTests : TestFixture { public void TheShortCtor_WritesAsEnglishDoes() { NumberFormat format = Grouping(",", 3, 3, "-"); CheckTrue(ReferenceEquals(PercentNotation.English, format.Percent)); CheckTrue(ReferenceEquals(TimeNotation.English, format.Time)); } public void Invariant_WritesAsEnglishDoes() { CheckTrue(ReferenceEquals(PercentNotation.English, NumberFormat.Invariant.Percent)); CheckTrue(ReferenceEquals(TimeNotation.English, NumberFormat.Invariant.Time)); } public void KeepsTheNotationsGiven() { var percent = new PercentNotation("pct", " ", signFirst: true); TimeNotation time = Notation(clockSeparator: "."); var format = new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", ShortNotation.English, percent, time); CheckTrue(ReferenceEquals(percent, format.Percent)); CheckTrue(ReferenceEquals(time, format.Time)); } public void ANullPercentNotation_Throws() { CheckThrow(typeof(ArgumentNullException)); new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", ShortNotation.English, null, TimeNotation.English); } public void ANullTimeNotation_Throws() { CheckThrow(typeof(ArgumentNullException)); new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", ShortNotation.English, PercentNotation.English, null); } public void FromCulture_TakesBothFromTheCulture() { var culture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); culture.NumberFormat.PercentSymbol = "pct"; culture.NumberFormat.PercentPositivePattern = 3; culture.DateTimeFormat.ShortTimePattern = "HH:mm"; NumberFormat format = NumberFormat.FromCulture(culture); CheckEqual("pct", format.Percent.Sign); CheckTrue(format.Percent.SignFirst); CheckTrue(format.Time.Prefers24Hours); } public void MaxPercentLength_IsAFixedNumberPlusTheSignAndGap() { NumberFormat format = WithPercent(new PercentNotation("pct", "__", signFirst: false)); CheckEqual(format.MaxFixedLength + 3 + 2, format.MaxPercentLength); } public void MaxClockLength_HoldsTheLongestClock() { NumberFormat format = WithTime(Notation(clockSeparator: "<:>", am: " ante", pm: " post meridiem")); CheckEqual(6 + 2 * 3 + 14, format.MaxClockLength); } public void MaxDurationLength_HoldsTheLongestDuration() { NumberFormat format = WithTime(Notation(day: "dd", hour: "hhh", minute: "m", second: "s", unitSeparator: "__")); CheckEqual(1 + 20 + 3 + 3 * (2 + 2 + 3), format.MaxDurationLength); } } public class WritePercentTests : TestFixture { public void AFraction_IsWrittenAsAPercent() { CheckEqual("25.6%", PercentOf(NumberFormat.Invariant, 0.256, 1)); } public void ZeroDecimals_RoundHalfAwayFromZero() { CheckEqual("26%", PercentOf(NumberFormat.Invariant, 0.256, 0)); CheckEqual("13%", PercentOf(NumberFormat.Invariant, 0.125, 0)); CheckEqual("-13%", PercentOf(NumberFormat.Invariant, -0.125, 0)); } public void TheDigits_ReadTheValueTo15SignificantDigits() { CheckEqual("12.35%", PercentOf(NumberFormat.Invariant, 0.12345, 2)); } public void WholeAndZero_AreWritten() { CheckEqual("100%", PercentOf(NumberFormat.Invariant, 1, 0)); CheckEqual("0%", PercentOf(NumberFormat.Invariant, 0, 0)); CheckEqual("0.0%", PercentOf(NumberFormat.Invariant, 0, 1)); } public void ACarry_GrowsTheWholePart() { CheckEqual("100.00%", PercentOf(NumberFormat.Invariant, 0.99996, 2)); } public void MoreThanAHundredPercent_IsGrouped() { CheckEqual("1,250%", PercentOf(NumberFormat.Invariant, 12.5, 0)); } public void Negative_WritesTheMinusSignFirst() { CheckEqual("-25.6%", PercentOf(NumberFormat.Invariant, -0.256, 1)); } public void ANegativeThatRoundsToZero_HasNoMinusSign() { CheckEqual("0%", PercentOf(NumberFormat.Invariant, -0.0004, 0)); } public void TheDecimalSeparatorAndGroups_AreTheFormats() { NumberFormat format = new NumberFormat(".", 3, 3, "~", ",", "NaN", "Infinity", "e", ShortNotation.English); CheckEqual("1.250,5%", PercentOf(format, 12.505, 1)); CheckEqual("~25,6%", PercentOf(format, -0.256, 1)); } public void AGap_FollowsTheDigits() { NumberFormat format = WithPercent(new PercentNotation("%", " ", signFirst: false)); CheckEqual("25.6 %", PercentOf(format, 0.256, 1)); CheckEqual("-25.6 %", PercentOf(format, -0.256, 1)); } public void ASignFirst_PrecedesTheDigits() { NumberFormat format = WithPercent(new PercentNotation("%", "", signFirst: true)); CheckEqual("%25.6", PercentOf(format, 0.256, 1)); } public void ASignFirstWithAGap_PutsTheGapAfterTheSign() { NumberFormat format = WithPercent(new PercentNotation("%", " ", signFirst: true)); CheckEqual("% 25.6", PercentOf(format, 0.256, 1)); } public void ASignFirst_FollowsTheMinusSign() { NumberFormat format = WithPercent(new PercentNotation("%", " ", signFirst: true)); CheckEqual("-% 25.6", PercentOf(format, -0.256, 1)); } public void ASignFirstThatRoundsToZero_HasNoMinusSign() { NumberFormat format = WithPercent(new PercentNotation("%", "", signFirst: true)); CheckEqual("%0", PercentOf(format, -0.0004, 0)); } public void ALongSign_IsWrittenInFull() { NumberFormat format = WithPercent(new PercentNotation("percent", " ", signFirst: false)); CheckEqual("50 percent", PercentOf(format, 0.5, 0)); } public void NaN_IsWrittenAsItsSymbolAlone() { CheckEqual("NaN", PercentOf(NumberFormat.Invariant, double.NaN, 1)); } public void Infinities_AreWrittenAsTheirSymbolsAlone() { CheckEqual("Infinity", PercentOf(NumberFormat.Invariant, double.PositiveInfinity, 1)); CheckEqual("-Infinity", PercentOf(NumberFormat.Invariant, double.NegativeInfinity, 1)); } public void AValueTooLargeForAFixedNumber_IsWrittenAsInfinity() { CheckEqual("Infinity", PercentOf(NumberFormat.Invariant, 1e300, 1)); CheckEqual("-Infinity", PercentOf(NumberFormat.Invariant, -1e300, 1)); } public void TheLargestPercent_FitsTheMaxLength() { NumberFormat wide = new NumberFormat("<->", 1, 1, "MINUS", "", "NaN", "Infinity", "e", ShortNotation.English, new PercentNotation("", "", signFirst: true), TimeNotation.English); var buffer = new char[wide.MaxPercentLength]; int end = wide.WritePercent(-7.8e26, NumberFormat.MaxPercentDecimals, buffer, 0); CheckTrue(end <= buffer.Length); } public void TheMostDecimals_AreWritten() { CheckEqual("12.3456789%", PercentOf(NumberFormat.Invariant, 0.123456789, 7)); } public void MoreDecimalsThanAPercentHolds_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); PercentOf(NumberFormat.Invariant, 0.5, NumberFormat.MaxPercentDecimals + 1); } public void NegativeDecimals_Throw() { CheckThrow(typeof(ArgumentOutOfRangeException)); PercentOf(NumberFormat.Invariant, 0.5, -1); } public void WritesAtThePositionGiven() { var buffer = new char[20]; buffer[0] = 'x'; int end = NumberFormat.Invariant.WritePercent(0.5, 0, buffer, 1); CheckEqual("x50%", new string(buffer, 0, end)); } } public class WriteClockTests : TestFixture { public const long OnePm = 13 * 3600 + 5 * 60; public void TheDefault_FollowsTheLanguage() { CheckEqual("1:05 PM", ClockOf(NumberFormat.Invariant, OnePm)); CheckEqual("12:00 AM", ClockOf(NumberFormat.Invariant, 0)); CheckEqual("12:00 PM", ClockOf(NumberFormat.Invariant, 12 * 3600)); CheckEqual("11:59 PM", ClockOf(NumberFormat.Invariant, 86399)); } public void ALanguageOf24Hours_IsWrittenOn24Hours() { NumberFormat format = WithTime(Notation(prefers24Hours: true, padsHour: true, showsMarker: false)); CheckEqual("13:05", ClockOf(format, OnePm)); CheckEqual("05:07", ClockOf(format, 5 * 3600 + 7 * 60)); CheckEqual("00:00", ClockOf(format, 0)); } public void Hours12_WritesAMarkerAndNoPadding() { CheckEqual("5:07 AM", ClockOf(NumberFormat.Invariant, 5 * 3600 + 7 * 60, ClockFormat.Hours12)); CheckEqual("1:05 PM", ClockOf(NumberFormat.Invariant, OnePm, ClockFormat.Hours12)); } public void Hours12NoMarker_WritesNoMarker() { CheckEqual("1:05", ClockOf(NumberFormat.Invariant, OnePm, ClockFormat.Hours12NoMarker)); CheckEqual("12:00", ClockOf(NumberFormat.Invariant, 0, ClockFormat.Hours12NoMarker)); } public void Hours24_PadsTheHour() { CheckEqual("13:05", ClockOf(NumberFormat.Invariant, OnePm, ClockFormat.Hours24)); CheckEqual("05:07", ClockOf(NumberFormat.Invariant, 5 * 3600 + 7 * 60, ClockFormat.Hours24)); CheckEqual("00:00", ClockOf(NumberFormat.Invariant, 0, ClockFormat.Hours24)); } public void Hours24_WritesNoMarkerEvenWhenAskedFor() { var format = ClockFormat.Hours24 with { Marker = ClockChoice.Yes }; CheckEqual("13:05", ClockOf(NumberFormat.Invariant, OnePm, format)); } public void APaddedHourOn12Hours_IsTwoDigits() { var format = ClockFormat.Hours12 with { PadHour = ClockChoice.Yes }; CheckEqual("05:07 AM", ClockOf(NumberFormat.Invariant, 5 * 3600 + 7 * 60, format)); CheckEqual("12:07 AM", ClockOf(NumberFormat.Invariant, 7 * 60, format)); } public void AnUnpaddedHourOn24Hours_IsAsLongAsItNeeds() { var format = ClockFormat.Hours24 with { PadHour = ClockChoice.No }; CheckEqual("5:07", ClockOf(NumberFormat.Invariant, 5 * 3600 + 7 * 60, format)); CheckEqual("0:00", ClockOf(NumberFormat.Invariant, 0, format)); } public void Seconds_FollowTheMinutes() { var format = new ClockFormat { Seconds = true }; CheckEqual("1:05:09 PM", ClockOf(NumberFormat.Invariant, OnePm + 9, format)); CheckEqual("11:59:59 PM", ClockOf(NumberFormat.Invariant, 86399, format)); } public void ATimePastADay_WrapsAround() { CheckEqual("1:05 PM", ClockOf(NumberFormat.Invariant, OnePm + 86400)); CheckEqual("1:05 PM", ClockOf(NumberFormat.Invariant, OnePm + 3 * 86400)); } public void ATimeBeforeMidnight_WrapsAround() { CheckEqual("11:00 PM", ClockOf(NumberFormat.Invariant, -3600)); CheckEqual("12:00 AM", ClockOf(NumberFormat.Invariant, -86400)); } public void TheMostExtremeTimes_Wrap() { ClockOf(NumberFormat.Invariant, long.MinValue); ClockOf(NumberFormat.Invariant, long.MaxValue); } public void AMarkerFirst_PrecedesTheDigits() { NumberFormat format = WithTime(Notation(clockSeparator: ".", am: "am ", pm: "pm ", markerFirst: true)); CheckEqual("pm 1.05", ClockOf(format, OnePm)); CheckEqual("am 12.00", ClockOf(format, 0)); } public void ALanguageOf24Hours_CanBeAskedFor12() { NumberFormat format = WithTime(Notation(prefers24Hours: true, padsHour: true, showsMarker: false)); CheckEqual("1:05 PM", ClockOf(format, OnePm, ClockFormat.Hours12)); CheckEqual("01:05", ClockOf(format, OnePm, new ClockFormat { Hours = ClockHours.Twelve })); } public void ALanguageOf12Hours_CanBeAskedFor24() { CheckEqual("13:05", ClockOf(NumberFormat.Invariant, OnePm, new ClockFormat { Hours = ClockHours.TwentyFour, PadHour = ClockChoice.Yes, })); } public void AMarkerCanBeTurnedOff() { var format = new ClockFormat { Marker = ClockChoice.No }; CheckEqual("1:05", ClockOf(NumberFormat.Invariant, OnePm, format)); } public void TheLongestClock_FitsTheMaxLength() { NumberFormat format = WithTime(Notation(clockSeparator: "<:>", am: " ante", pm: " post meridiem")); var buffer = new char[format.MaxClockLength]; var clock = ClockFormat.Hours12 with { Seconds = true, PadHour = ClockChoice.Yes }; for (long second = 0; second < 86400; second += 61) { format.WriteClock(second, clock, buffer, 0); } } public void EveryChoice_FitsTheMaxLengthAtEveryTime() { var buffer = new char[NumberFormat.Invariant.MaxClockLength]; foreach (ClockHours hours in new[] { ClockHours.Language, ClockHours.Twelve, ClockHours.TwentyFour }) { foreach (ClockChoice marker in new[] { ClockChoice.Language, ClockChoice.Yes, ClockChoice.No }) { foreach (ClockChoice pad in new[] { ClockChoice.Language, ClockChoice.Yes, ClockChoice.No }) { var clock = new ClockFormat { Hours = hours, Marker = marker, PadHour = pad, Seconds = true, }; for (long second = 0; second < 86400; second += 997) { NumberFormat.Invariant.WriteClock(second, clock, buffer, 0); } } } } } public void WritesAtThePositionGiven() { var buffer = new char[20]; buffer[0] = 'x'; int end = NumberFormat.Invariant.WriteClock(OnePm, ClockFormat.Hours24, buffer, 1); CheckEqual("x13:05", new string(buffer, 0, end)); } } public class WriteDurationTests : TestFixture { public const long HourAndFiveMinutes = 3900; public void TheDefault_WritesHoursAndMinutes() { CheckEqual("1h 5m", DurationOf(NumberFormat.Invariant, HourAndFiveMinutes)); } public void TheLargestUnitThatIsntZero_Starts() { CheckEqual("5m", DurationOf(NumberFormat.Invariant, 300)); } public void ZeroUnitsBetween_AreWritten() { CheckEqual("1h 0m", DurationOf(NumberFormat.Invariant, 3600)); } public void Zero_IsWrittenInTheSmallestUnit() { var seconds = new DurationFormat { Smallest = DurationUnit.Seconds }; CheckEqual("0m", DurationOf(NumberFormat.Invariant, 0)); CheckEqual("0s", DurationOf(NumberFormat.Invariant, 0, seconds)); } public void WhatIsBelowTheSmallestUnit_IsDropped() { CheckEqual("0m", DurationOf(NumberFormat.Invariant, 59)); CheckEqual("1m", DurationOf(NumberFormat.Invariant, 119)); } public void PaddingWithAZero_PadsTheAmountsAfterTheFirst() { var format = new DurationFormat { Pad = DurationPad.Zero }; CheckEqual("1h 05m", DurationOf(NumberFormat.Invariant, HourAndFiveMinutes, format)); CheckEqual("1h 00m", DurationOf(NumberFormat.Invariant, 3600, format)); CheckEqual("1h 10m", DurationOf(NumberFormat.Invariant, 4200, format)); } public void PaddingWithASpace_PadsTheAmountsAfterTheFirst() { var format = new DurationFormat { Pad = DurationPad.Space }; CheckEqual("1h 5m", DurationOf(NumberFormat.Invariant, HourAndFiveMinutes, format)); CheckEqual("1h 10m", DurationOf(NumberFormat.Invariant, 4200, format)); } public void PaddingNeverTouchesTheFirstAmount() { var format = new DurationFormat { Pad = DurationPad.Zero }; CheckEqual("5m", DurationOf(NumberFormat.Invariant, 300, format)); } public void SecondsAsTheSmallestUnit_AreWritten() { var format = new DurationFormat { Smallest = DurationUnit.Seconds }; CheckEqual("1h 5m 5s", DurationOf(NumberFormat.Invariant, 3905, format)); CheckEqual("1m 5s", DurationOf(NumberFormat.Invariant, 65, format)); CheckEqual("5s", DurationOf(NumberFormat.Invariant, 5, format)); } public void PaddedSeconds_ArePaddedToo() { var format = new DurationFormat { Smallest = DurationUnit.Seconds, Pad = DurationPad.Zero }; CheckEqual("1h 05m 05s", DurationOf(NumberFormat.Invariant, 3905, format)); } public void MinutesAsTheLargestUnit_TakeAllTheHours() { var format = new DurationFormat { Largest = DurationUnit.Minutes }; CheckEqual("125m", DurationOf(NumberFormat.Invariant, 7500, format)); } public void SecondsAsTheLargestUnit_ImplyTheSmallestIsSeconds() { var format = new DurationFormat { Largest = DurationUnit.Seconds }; CheckEqual("125s", DurationOf(NumberFormat.Invariant, 125, format)); } public void DaysAsTheLargestUnit_AreWritten() { var format = new DurationFormat { Largest = DurationUnit.Days }; CheckEqual("1d 1h 1m", DurationOf(NumberFormat.Invariant, 90061, format)); } public void TheDefaultLargestUnit_TakesAllTheDays() { CheckEqual("25h 1m", DurationOf(NumberFormat.Invariant, 90061)); } public void AllFourUnits_AreWritten() { var format = new DurationFormat { Largest = DurationUnit.Days, Smallest = DurationUnit.Seconds }; CheckEqual("1d 1h 1m 1s", DurationOf(NumberFormat.Invariant, 90061, format)); } public void HoursAsTheSmallestUnit_DropTheMinutes() { var format = new DurationFormat { Smallest = DurationUnit.Hours }; CheckEqual("2h", DurationOf(NumberFormat.Invariant, 7500, format)); } public void DaysAsTheSmallestUnit_ImplyTheLargestIsDays() { var format = new DurationFormat { Smallest = DurationUnit.Days }; CheckEqual("1d", DurationOf(NumberFormat.Invariant, 90000, format)); } public void Negative_WritesTheMinusSignFirst() { CheckEqual("-1h 5m", DurationOf(NumberFormat.Invariant, -HourAndFiveMinutes)); } public void ANegativeThatWritesOnlyZeros_HasNoMinusSign() { CheckEqual("0m", DurationOf(NumberFormat.Invariant, -30)); CheckEqual("-1m", DurationOf(NumberFormat.Invariant, -90)); } public void TheMinusSign_IsTheFormats() { NumberFormat format = new NumberFormat(",", 3, 3, "MINUS", ".", "NaN", "Infinity", "e", ShortNotation.English); CheckEqual("MINUS5m", DurationOf(format, -300)); } public void TheUnitsAndSeparator_AreTheNotations() { NumberFormat format = WithTime(Notation(day: "J", hour: "Std", minute: "Min", second: "Sek", unitSeparator: "_")); var duration = new DurationFormat { Largest = DurationUnit.Days, Smallest = DurationUnit.Seconds }; CheckEqual("1J_1Std_1Min_1Sek", DurationOf(format, 90061, duration)); } public void AnEmptySeparatorAndUnits_AreWrittenAsGiven() { NumberFormat format = WithTime(Notation(hour: "", minute: "", unitSeparator: "")); CheckEqual("15", DurationOf(format, HourAndFiveMinutes)); } public void TheLargestDurations_FitTheMaxLength() { var duration = new DurationFormat { Largest = DurationUnit.Days, Smallest = DurationUnit.Seconds }; var seconds = new DurationFormat { Largest = DurationUnit.Seconds }; CheckTrue(DurationOf(NumberFormat.Invariant, long.MaxValue, duration) .StartsWith("106751991167300d 15h")); DurationOf(NumberFormat.Invariant, long.MinValue, duration); DurationOf(NumberFormat.Invariant, long.MinValue, seconds); DurationOf(NumberFormat.Invariant, long.MaxValue, seconds); } public void AnInconsistentFormat_Throws() { var format = new DurationFormat { Largest = DurationUnit.Minutes, Smallest = DurationUnit.Hours }; CheckThrow(typeof(ArgumentException)); DurationOf(NumberFormat.Invariant, 60, format); } public void WritesAtThePositionGiven() { var buffer = new char[30]; buffer[0] = 'x'; int end = NumberFormat.Invariant.WriteDuration(HourAndFiveMinutes, default, buffer, 1); CheckEqual("x1h 5m", new string(buffer, 0, end)); } } public const int ArabicIndicZero = 0x0660; public const int MathematicalBoldZero = 0x1D7CE; public static NumberFormat Shaped(int zeroDigit) { return new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", ShortNotation.English, PercentNotation.English, TimeNotation.English, zeroDigit); } // Spells ASCII digits in the mathematical bold digits, which sit beyond the Basic Multilingual Plane. public static string Bold(string text) { var returnMe = new System.Text.StringBuilder(); foreach (char letter in text) { if (letter >= '0' && letter <= '9') { returnMe.Append(char.ConvertFromUtf32(MathematicalBoldZero + letter - '0')); } else { returnMe.Append(letter); } } return returnMe.ToString(); } public class DigitShapeCtorTests : TestFixture { public void TheOlderConstructors_WriteAsciiDigits() { CheckEqual((int)'0', NumberFormat.Invariant.ZeroDigit); CheckEqual(1, NumberFormat.Invariant.DigitWidth); CheckEqual((int)'0', WithPercent(PercentNotation.English).ZeroDigit); } public void KeepsTheZeroAndTakesOneCharacterForABasicDigit() { NumberFormat format = Shaped(ArabicIndicZero); CheckEqual(ArabicIndicZero, format.ZeroDigit); CheckEqual(1, format.DigitWidth); } public void ADigitBeyondTheBasicPlane_TakesTwoCharacters() { NumberFormat format = Shaped(MathematicalBoldZero); CheckEqual(MathematicalBoldZero, format.ZeroDigit); CheckEqual(2, format.DigitWidth); } public void ANegativeZero_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); Shaped(-1); } public void ADigitSetPastTheLastCodePoint_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); Shaped(0x10FFF7); } public void TheLastDigitSetThatFits_IsKept() { CheckEqual(2, Shaped(0x10FFF6).DigitWidth); } public void ADigitSetInsideTheSurrogates_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); Shaped(0xD800); } public void ADigitSetThatRunsIntoTheSurrogates_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); Shaped(0xD7FA); } public void ADigitSetThatLeavesTheSurrogates_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); Shaped(0xDFFF); } public void ADigitSetRightBesideTheSurrogates_IsKept() { CheckEqual(0xD7F6, Shaped(0xD7F6).ZeroDigit); CheckEqual(0xE000, Shaped(0xE000).ZeroDigit); } public void ADigitSetThatCrossesTheBasicPlane_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); Shaped(0xFFF7); } public void ADigitSetThatEndsAtTheEndOfTheBasicPlane_IsKept() { CheckEqual(1, Shaped(0xFFF6).DigitWidth); } } public class DigitShapeWriteTests : TestFixture { public void Count_WritesTheDigitsAndKeepsTheSeparators() { NumberFormat format = Shaped(ArabicIndicZero); CheckEqual("١,٢٣٤,٥٦٧", CountOf(format, 1234567)); CheckEqual("-٥", CountOf(format, -5)); CheckEqual("٠", CountOf(format, 0)); } public void Count_WritesEveryDigit() { CheckEqual("١,٢٣٤,٥٦٧,٨٩٠", CountOf(Shaped(ArabicIndicZero), 1234567890)); } public void Count_WritesTheLargestNumber() { CheckEqual("٩,٢٢٣,٣٧٢,٠٣٦,٨٥٤,٧٧٥,٨٠٧", CountOf(Shaped(ArabicIndicZero), long.MaxValue)); } public void Count_WritesTheMostNegativeNumber() { CheckEqual("-٩,٢٢٣,٣٧٢,٠٣٦,٨٥٤,٧٧٥,٨٠٨", CountOf(Shaped(ArabicIndicZero), long.MinValue)); } public void Count_WritesTwoCharactersADigitBeyondTheBasicPlane() { NumberFormat format = Shaped(MathematicalBoldZero); CheckEqual(Bold("1,234,567"), CountOf(format, 1234567)); CheckEqual(Bold("-5"), CountOf(format, -5)); CheckEqual(Bold("9,223,372,036,854,775,807"), CountOf(format, long.MaxValue)); } public void Fixed_WritesTheWholePartAndTheDecimals() { CheckEqual("١٢.٥٠", FixedOf(Shaped(ArabicIndicZero), 12.5, 2)); CheckEqual(Bold("1,000.050"), FixedOf(Shaped(MathematicalBoldZero), 1000.05, 3)); } public void Scientific_WritesTheMantissaAndTheExponent() { CheckEqual("١.٥e١٠", ScientificOf(Shaped(ArabicIndicZero), 1.5e10, 2)); CheckEqual("-٢e-٥", ScientificOf(Shaped(ArabicIndicZero), -2e-5, 1)); CheckEqual(Bold("1.5e10"), ScientificOf(Shaped(MathematicalBoldZero), 1.5e10, 2)); } public void Short_WritesTheWholePartAndTheFraction() { CheckEqual("١.٢K", ShortOf(Shaped(ArabicIndicZero), 1234, 2)); CheckEqual(Bold("1.2K"), ShortOf(Shaped(MathematicalBoldZero), 1234, 2)); } public void Short_WritesAValueBelowOneWithItsLeadingZeros() { CheckEqual("٠.٠٠٣", ShortOf(Shaped(ArabicIndicZero), 0.003, 1)); CheckEqual(Bold("0.003"), ShortOf(Shaped(MathematicalBoldZero), 0.003, 1)); } public void Percent_WritesTheDigitsBesideTheSign() { CheckEqual("٢٥.٦%", PercentOf(Shaped(ArabicIndicZero), 0.256, 1)); } public void Clock_WritesThePaddingAndTheMinutes() { NumberFormat format = Shaped(ArabicIndicZero); CheckEqual("٠٥:٠٧", ClockOf(format, 5 * 3600 + 7 * 60, ClockFormat.Hours24)); CheckEqual("١:٠٥ PM", ClockOf(format, 13 * 3600 + 5 * 60)); CheckEqual(Bold("05:07"), ClockOf(Shaped(MathematicalBoldZero), 5 * 3600 + 7 * 60, ClockFormat.Hours24)); } public void Duration_WritesThePaddingAndTheAmounts() { var padded = new DurationFormat { Pad = DurationPad.Zero }; CheckEqual("١h ٠٥m", DurationOf(Shaped(ArabicIndicZero), 3900, padded)); CheckEqual(Bold("1h 05m"), DurationOf(Shaped(MathematicalBoldZero), 3900, padded)); } public void WritesAtThePositionGiven() { var buffer = new char[20]; buffer[0] = 'x'; int end = Shaped(MathematicalBoldZero).WriteCount(42, buffer, 1); CheckEqual("x" + Bold("42"), new string(buffer, 0, end)); } } public class DigitShapeMaxLengthTests : TestFixture { public void TheWidestCount_FitsTheMaxCountLength() { NumberFormat format = Shaped(MathematicalBoldZero); CheckTrue(CountOf(format, long.MinValue).Length <= format.MaxCountLength); } public void TheLongestFixed_FitsTheMaxFixedLength() { NumberFormat format = Shaped(MathematicalBoldZero); CheckTrue(FixedOf(format, -7.9e28, NumberFormat.MaxDecimals).Length <= format.MaxFixedLength); } public void TheLongestScientific_FitsTheMaxScientificLength() { NumberFormat format = Shaped(MathematicalBoldZero); CheckTrue(ScientificOf(format, -1.23456789012345e-300, NumberFormat.MaxSignificantDigits).Length <= format.MaxScientificLength); } public void TheLongestShort_FitsTheMaxShortLength() { NumberFormat format = Shaped(MathematicalBoldZero); CheckTrue(ShortOf(format, -0.00012345678901234, NumberFormat.MaxSignificantDigits).Length <= format.MaxShortLength); CheckTrue(ShortOf(format, -123456789012345e3, NumberFormat.MaxSignificantDigits).Length <= format.MaxShortLength); } public void ThePercentWithMostDecimals_FitsTheMaxPercentLength() { NumberFormat format = Shaped(MathematicalBoldZero); CheckTrue(PercentOf(format, -1e20, NumberFormat.MaxPercentDecimals).Length <= format.MaxPercentLength); } public void TheLongestClock_FitsTheMaxClockLength() { NumberFormat format = Shaped(MathematicalBoldZero); var clock = new ClockFormat { Hours = ClockHours.Twelve, Seconds = true }; CheckTrue(ClockOf(format, 11 * 3600 + 59 * 60 + 59, clock).Length <= format.MaxClockLength); } public void TheLongestDuration_FitsTheMaxDurationLength() { NumberFormat format = Shaped(MathematicalBoldZero); var padded = new DurationFormat { Pad = DurationPad.Zero, Largest = DurationUnit.Days, Smallest = DurationUnit.Seconds }; CheckTrue(DurationOf(format, long.MinValue + 1, padded).Length <= format.MaxDurationLength); } } public static readonly string NoBreakSpace = ((char)0xA0).ToString(); public static readonly string NarrowNoBreakSpace = ((char)0x202F).ToString(); public static NumberFormat Grouped(int primarySize, int secondarySize, int minimumGroupingDigits) { return new NumberFormat(",", primarySize, secondarySize, "-", ".", "NaN", "Infinity", "e", ShortNotation.English, PercentNotation.English, TimeNotation.English, '0', minimumGroupingDigits); } public class MinimumGroupingDigitsTests : TestFixture { public void IsOneUnlessGiven() { CheckEqual(1, NumberFormat.Invariant.MinimumGroupingDigits); CheckEqual(1, Shaped(ArabicIndicZero).MinimumGroupingDigits); } public void IsKept() { CheckEqual(2, Grouped(3, 3, 2).MinimumGroupingDigits); } public void Zero_Throws() { CheckThrow(typeof(ArgumentOutOfRangeException)); Grouped(3, 3, 0); } public void ANumberShorterThanAGroupPlusTheMinimum_IsNotGrouped() { NumberFormat format = Grouped(3, 3, 2); CheckEqual("1234", CountOf(format, 1234)); CheckEqual("-1234", CountOf(format, -1234)); CheckEqual("999", CountOf(format, 999)); } public void ANumberAsLongAsAGroupPlusTheMinimum_IsGrouped() { NumberFormat format = Grouped(3, 3, 2); CheckEqual("12,345", CountOf(format, 12345)); CheckEqual("-12,345", CountOf(format, -12345)); CheckEqual("1,234,567", CountOf(format, 1234567)); } public void AMinimumOfThree_LeavesFiveDigitsAlone() { NumberFormat format = Grouped(3, 3, 3); CheckEqual("12345", CountOf(format, 12345)); CheckEqual("123,456", CountOf(format, 123456)); } public void TheWholePartOfAFixedNumber_FollowsIt() { NumberFormat format = Grouped(3, 3, 2); CheckEqual("1234.5", FixedOf(format, 1234.5, 1)); CheckEqual("12,345.5", FixedOf(format, 12345.5, 1)); } public void WithASmallerSecondGroup_GroupsAllTheDigitsOnceItStarts() { NumberFormat format = Grouped(3, 2, 2); CheckEqual("1234", CountOf(format, 1234)); CheckEqual("12,345", CountOf(format, 12345)); CheckEqual("12,34,567", CountOf(format, 1234567)); } public void WithNoGroups_ChangesNothing() { CheckEqual("1234567", CountOf(Grouped(0, 0, 2), 1234567)); } public void TheWidestCount_FitsTheMaxCountLength() { NumberFormat format = Grouped(3, 3, 2); CheckTrue(CountOf(format, long.MinValue).Length <= format.MaxCountLength); } } public class TryForTests : TestFixture { public void ALanguageCldrHas_IsFound() { CheckTrue(NumberFormat.TryFor("de", out NumberFormat format)); CheckEqual(".", format.GroupSeparator); CheckEqual(",", format.DecimalSeparator); } public void ARegionCldrHas_IsFoundBeforeItsLanguage() { NumberFormat.TryFor("de-CH", out NumberFormat swiss); CheckEqual("'", swiss.GroupSeparator); CheckEqual(".", swiss.DecimalSeparator); } public void ARegionItLacks_FallsBackToTheLanguage() { NumberFormat.TryFor("de-XX", out NumberFormat format); CheckEqual(".", format.GroupSeparator); } public void AScriptAndRegionItLacks_FallBackToTheLanguageWithTheScript() { NumberFormat.TryFor("zh-Hant-TW", out NumberFormat format); CheckEqual("非數值", format.NotANumberSymbol); } public void TheTagIsReadWhateverItsCaseAndSeparator() { NumberFormat.TryFor("DE_ch", out NumberFormat format); CheckEqual("'", format.GroupSeparator); } public void ARegionOnlyTagForAScriptThatIsntTheDefault_IsFound() { NumberFormat.TryFor("zh-TW", out NumberFormat taiwan); NumberFormat.TryFor("zh-CN", out NumberFormat china); CheckEqual("非數值", taiwan.NotANumberSymbol); CheckEqual("NaN", china.NotANumberSymbol); } public void ALanguageCldrLacks_IsNotFound() { CheckFalse(NumberFormat.TryFor("xx", out NumberFormat format)); CheckNull(format); } public void AnEmptyTag_IsNotFound() { CheckFalse(NumberFormat.TryFor("", out NumberFormat format)); CheckNull(format); } public void ANullTag_Throws() { CheckThrow(typeof(ArgumentNullException)); NumberFormat.TryFor(null, out _); } public void LanguagesThatWriteAlike_ShareAFormat() { NumberFormat.TryFor("fr", out NumberFormat french); NumberFormat.TryFor("fr-BF", out NumberFormat burkinaFaso); CheckTrue(ReferenceEquals(french, burkinaFaso)); } } public class ForTagTests : TestFixture { public void English_WritesCommasAndAPeriod() { NumberFormat format = NumberFormat.For("en"); CheckEqual("1,234,567", CountOf(format, 1234567)); CheckEqual("12.5", FixedOf(format, 12.5, 1)); } public void German_WritesPeriodsAndACommaAndASpacedPercent() { NumberFormat format = NumberFormat.For("de"); CheckEqual("1.234.567", CountOf(format, 1234567)); CheckEqual("12,5", FixedOf(format, 12.5, 1)); CheckEqual("25,6" + NoBreakSpace + "%", PercentOf(format, 0.256, 1)); } public void French_GroupsWithANarrowNoBreakSpace() { NumberFormat format = NumberFormat.For("fr"); CheckEqual("1" + NarrowNoBreakSpace + "234" + NarrowNoBreakSpace + "567", CountOf(format, 1234567)); CheckEqual("25,6" + NoBreakSpace + "%", PercentOf(format, 0.256, 1)); } public void Spanish_LeavesFourDigitsUngrouped() { NumberFormat format = NumberFormat.For("es"); CheckEqual("1234", CountOf(format, 1234)); CheckEqual("12.345", CountOf(format, 12345)); } public void Hindi_GroupsByThreeThenTwoInLatinDigits() { CheckEqual("12,34,567", CountOf(NumberFormat.For("hi"), 1234567)); } public void Turkish_PutsThePercentSignFirst() { CheckEqual("%25,6", PercentOf(NumberFormat.For("tr"), 0.256, 1)); } public void Swedish_WritesATrueMinusSignAndAWordyExponent() { NumberFormat format = NumberFormat.For("sv"); CheckEqual("−" + "5", CountOf(format, -5)); CheckEqual("1,5×10^10", ScientificOf(format, 1.5e10, 2)); } public void Arabic_ForEgyptWritesArabicIndicDigits() { NumberFormat format = NumberFormat.For("ar-EG"); CheckEqual(0x0660, format.ZeroDigit); CheckEqual("١٬٢٣٤٬٥٦٧", CountOf(format, 1234567)); } public void Arabic_ForTheEmiratesWritesLatinDigits() { CheckEqual((int)'0', NumberFormat.For("ar-AE").ZeroDigit); } public void Persian_WritesExtendedArabicIndicDigits() { CheckEqual(0x06F0, NumberFormat.For("fa").ZeroDigit); } public void Bengali_WritesBengaliDigits() { CheckEqual(0x09E6, NumberFormat.For("bn").ZeroDigit); } public void Burmese_WritesBurmeseDigits() { CheckEqual(0x1040, NumberFormat.For("my").ZeroDigit); } public void Adlam_WritesDigitsBeyondTheBasicPlane() { NumberFormat.TryFor("ff-Adlm", out NumberFormat format); CheckEqual(0x1E950, format.ZeroDigit); CheckEqual(2, format.DigitWidth); } public void ALanguageCldrLacks_IsInvariant() { CheckTrue(ReferenceEquals(NumberFormat.Invariant, NumberFormat.For("xx"))); } public void ANullTag_Throws() { CheckThrow(typeof(ArgumentNullException)); NumberFormat.For((string)null); } public void TheShortNotation_IsTheLanguages() { NumberFormat format = NumberFormat.For("de"); CheckEqual(0, format.ShortNotation.TierOf(3).Shift); CheckEqual(6, format.ShortNotation.TierOf(6).Shift); } public void TheTime_IsTheLanguages() { NumberFormat format = NumberFormat.For("de"); CheckTrue(format.Time.Prefers24Hours); CheckEqual(", ", format.Time.UnitSeparator); CheckEqual(" Min.", format.Time.MinuteUnit.After); } public void EveryLanguageWritesAWholeNumberWithinItsMaxLength() { string[] tags = { "ar-EG", "bn", "fa", "ff-Adlm", "my", "hi", "fr", "es", "sv" }; foreach (string tag in tags) { NumberFormat format = NumberFormat.For(tag); CheckTrue(CountOf(format, long.MinValue).Length <= format.MaxCountLength); CheckTrue(FixedOf(format, -7.8e28, NumberFormat.MaxDecimals).Length <= format.MaxFixedLength); CheckTrue(PercentOf(format, -1e20, NumberFormat.MaxPercentDecimals).Length <= format.MaxPercentLength); } } } public class ForCultureTests : TestFixture { public void ACultureCldrHas_TakesItsNumbers() { CheckEqual("1.234.567", CountOf(NumberFormat.For(new CultureInfo("de-DE")), 1234567)); } public void ACultureCldrHas_TakesItsTimeFromTheCulture() { var culture = new CultureInfo("de-DE"); CheckEqual(TimeNotation.FromCulture(culture).Prefers24Hours, NumberFormat.For(culture).Time.Prefers24Hours); } public void ACultureCldrHas_TakesItsDurationsFromCldr() { NumberFormat format = NumberFormat.For(new CultureInfo("de-DE")); CheckEqual(", ", format.Time.UnitSeparator); CheckEqual(" Min.", format.Time.MinuteUnit.After); } public void ACultureCldrHas_TakesItsShortSuffixesFromCldr() { CheckEqual(NumberFormat.For("de").ShortNotation, NumberFormat.For(new CultureInfo("de-DE")).ShortNotation); } public void ACultureWhoseClockDiffersFromCldrs_WritesItsOwnClock() { var culture = new CultureInfo("de-DE"); culture.DateTimeFormat.ShortTimePattern = "h:mm tt"; culture.DateTimeFormat.AMDesignator = "vorm."; culture.DateTimeFormat.PMDesignator = "nachm."; NumberFormat format = NumberFormat.For(culture); CheckFalse(format.Time.Prefers24Hours); CheckEqual(" vorm.", format.Time.AmMarker); CheckEqual(" nachm.", format.Time.PmMarker); CheckEqual(" Min.", format.Time.MinuteUnit.After); } public void TheInvariantCulture_ReadsDotNet() { CheckEqual("1,234,567", CountOf(NumberFormat.For(CultureInfo.InvariantCulture), 1234567)); } public void ARegionalCulture_TakesItsRegionsNumbers() { CheckEqual("1'234'567", CountOf(NumberFormat.For(new CultureInfo("de-CH")), 1234567)); } public void ANullCulture_Throws() { CheckThrow(typeof(ArgumentNullException)); NumberFormat.For((CultureInfo)null); } } public class WithTimeTests : TestFixture { public void ChangesOnlyTheTime() { NumberFormat original = NumberFormat.For("ar-EG"); TimeNotation time = Notation(prefers24Hours: true); NumberFormat changed = original.WithTime(time); CheckTrue(ReferenceEquals(time, changed.Time)); CheckEqual(original.ZeroDigit, changed.ZeroDigit); CheckEqual(original.GroupSeparator, changed.GroupSeparator); CheckEqual(original.MinimumGroupingDigits, changed.MinimumGroupingDigits); CheckTrue(ReferenceEquals(original.Percent, changed.Percent)); CheckEqual(time.MaxClockLength(original.DigitWidth), changed.MaxClockLength); } public void KeepsTheMinimumGroupingDigits() { CheckEqual(2, NumberFormat.For("es").WithTime(TimeNotation.English).MinimumGroupingDigits); } public void ANullTime_Throws() { CheckThrow(typeof(ArgumentNullException)); NumberFormat.Invariant.WithTime(null); } } public class TryScientificNumberTests : TestFixture { public void ReadsTheMantissaAndExponent() { CheckTrue(NumberFormat.TryScientificNumber(1234, 3, out CompactNumber number)); CheckFalse(number.IsNegative); CheckEqual(1.23m, number.Significand); CheckEqual(2, number.Decimals); CheckEqual(3, number.Exponent); } public void ANegativeValue_IsMarkedNegative() { CheckTrue(NumberFormat.TryScientificNumber(-1234, 3, out CompactNumber number)); CheckTrue(number.IsNegative); CheckEqual(1.23m, number.Significand); } public void ZeroHasAnExponentOfZero() { CheckTrue(NumberFormat.TryScientificNumber(0, 2, out CompactNumber number)); CheckEqual(0m, number.Significand); CheckEqual(1, number.Decimals); CheckEqual(0, number.Exponent); } public void RoundingUpToTen_CarriesIntoTheExponent() { CheckTrue(NumberFormat.TryScientificNumber(9.99, 2, out CompactNumber number)); CheckEqual(1m, number.Significand); CheckEqual(1, number.Decimals); CheckEqual(1, number.Exponent); } public void ASmallValue_HasANegativeExponent() { CheckTrue(NumberFormat.TryScientificNumber(0.0015, 2, out CompactNumber number)); CheckEqual(1.5m, number.Significand); CheckEqual(-3, number.Exponent); } public void NaNAndInfinity_AreNotNumbers() { CheckFalse(NumberFormat.TryScientificNumber(double.NaN, 3, out _)); CheckFalse(NumberFormat.TryScientificNumber(double.NegativeInfinity, 3, out _)); } public void DigitsOutOfRange_Throw() { CheckThrow(typeof(ArgumentOutOfRangeException)); NumberFormat.TryScientificNumber(1, 0, out _); } public void TooManyDigits_Throw() { CheckThrow(typeof(ArgumentOutOfRangeException)); NumberFormat.TryScientificNumber(1, NumberFormat.MaxSignificantDigits + 1, out _); } } public class TryShortNumberTests : TestFixture { public void ASuffixedValue_HasTheSuffixsPowerOfTenAsItsExponent() { CheckTrue(NumberFormat.Invariant.TryShortNumber(1234567, 3, out CompactNumber number)); CheckEqual(1.23m, number.Significand); CheckEqual(2, number.Decimals); CheckEqual(6, number.Exponent); } public void TheWholePartIsNeverCutShort() { CheckTrue(NumberFormat.Invariant.TryShortNumber(123456, 2, out CompactNumber number)); CheckEqual(123m, number.Significand); CheckEqual(0, number.Decimals); CheckEqual(3, number.Exponent); } public void ASuffixStepOfFour_ShiftsTheWholePart() { var format = new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", ShortNotation.FromGroups(new[] { "man" }, "", 4)); CheckTrue(format.TryShortNumber(12345678, 3, out CompactNumber number)); CheckEqual(1235m, number.Significand); CheckEqual(0, number.Decimals); CheckEqual(4, number.Exponent); } public void AValueBelowTheFirstSuffix_IsWrittenOut() { CheckTrue(NumberFormat.Invariant.TryShortNumber(12, 3, out CompactNumber number)); CheckEqual(12m, number.Significand); CheckEqual(1, number.Decimals); CheckEqual(0, number.Exponent); } public void AValueBelowOne_IsWrittenOutDownToItsLastDecimal() { CheckTrue(NumberFormat.Invariant.TryShortNumber(0.0012, 2, out CompactNumber number)); CheckEqual(0.0012m, number.Significand); CheckEqual(4, number.Decimals); CheckEqual(0, number.Exponent); } public void AValueBelowTheLastWrittenDecimal_IsScientific() { CheckTrue(NumberFormat.Invariant.TryShortNumber(0.00001, 2, out CompactNumber number)); CheckEqual(1m, number.Significand); CheckEqual(-5, number.Exponent); } public void AValuePastTheLastSuffix_IsScientific() { CheckTrue(NumberFormat.Invariant.TryShortNumber(1e45, 2, out CompactNumber number)); CheckEqual(1m, number.Significand); CheckEqual(45, number.Exponent); } public void RoundingUpToTheNextSuffix_CarriesIntoTheExponent() { CheckTrue(NumberFormat.Invariant.TryShortNumber(999999, 2, out CompactNumber number)); CheckEqual(1m, number.Significand); CheckEqual(1, number.Decimals); CheckEqual(6, number.Exponent); } public void ANegativeValue_IsMarkedNegative() { CheckTrue(NumberFormat.Invariant.TryShortNumber(-1500, 2, out CompactNumber number)); CheckTrue(number.IsNegative); CheckEqual(1.5m, number.Significand); } public void ZeroIsWrittenOut() { CheckTrue(NumberFormat.Invariant.TryShortNumber(0, 3, out CompactNumber number)); CheckEqual(0m, number.Significand); CheckEqual(2, number.Decimals); CheckEqual(0, number.Exponent); } public void NaNAndInfinity_AreNotNumbers() { CheckFalse(NumberFormat.Invariant.TryShortNumber(double.NaN, 3, out _)); CheckFalse(NumberFormat.Invariant.TryShortNumber(double.PositiveInfinity, 3, out _)); } public void DigitsOutOfRange_Throw() { CheckThrow(typeof(ArgumentOutOfRangeException)); NumberFormat.Invariant.TryShortNumber(1, 0, out _); } } public class WriteClockPatternTests : TestFixture { public const long OnePm = 13 * 3600 + 5 * 60; public const long OnePmAndSevenSeconds = OnePm + 7; public const long MidnightFive = 5 * 60; public static readonly ClockFormat Hours24WithSeconds = new ClockFormat { Hours = ClockHours.TwentyFour, PadHour = ClockChoice.Yes, Seconds = true, }; public void APatternsPrefixAndSuffix_AreWrittenAroundTheClock() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(pattern24: "'Kl. 'HH:mm' Uhr'")); CheckEqual("Kl. 13:05 Uhr", ClockOf(format, OnePm, ClockFormat.Hours24)); } public void ThePatternWithSeconds_HasItsOwnSeparatorsAndSuffix() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(pattern24: "HH 'h' mm", pattern24WithSeconds: "HH 'h' mm 'min' ss 's'")); CheckEqual("13 h 05", ClockOf(format, OnePm, ClockFormat.Hours24)); CheckEqual("13 h 05 min 07 s", ClockOf(format, OnePmAndSevenSeconds, Hours24WithSeconds)); } public void TheTwelveHourPattern_HasItsOwnSeparators() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(pattern24: "H.mm", pattern12: "h:mm a")); CheckEqual("13.05", ClockOf(format, OnePm, ClockFormat.Hours24)); CheckEqual("1:05 PM", ClockOf(format, OnePm, ClockFormat.Hours12)); } public void HoursCountedFromZero_ShowMidnightAsZero() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(pattern12: "aK:mm", pattern12WithSeconds: "aK:mm:ss", am: "am", pm: "pm")); CheckEqual("am0:05", ClockOf(format, MidnightFive, ClockFormat.Hours12)); CheckEqual("pm0:05", ClockOf(format, 12 * 3600 + 5 * 60, ClockFormat.Hours12)); CheckEqual("pm1:05", ClockOf(format, OnePm, ClockFormat.Hours12)); } public void HoursCountedFromOneToTwentyFour_ShowMidnightAs24() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(pattern24: "k:mm")); CheckEqual("24:05", ClockOf(format, MidnightFive, ClockFormat.Hours24)); CheckEqual("13:05", ClockOf(format, OnePm, ClockFormat.Hours24)); } public void TheGapBeforeAMarker_IsWrittenWithIt() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(pattern12: "h:mm '~' a")); CheckEqual("1:05 ~ PM", ClockOf(format, OnePm, ClockFormat.Hours12)); } public void TheGapBeforeAMarker_GoesWhenTheMarkerDoes() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(pattern12: "h:mm '~' a")); CheckEqual("1:05", ClockOf(format, OnePm, ClockFormat.Hours12NoMarker)); } public void TheGapAfterAMarkerThatIsFirst_IsWrittenWithIt() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(pattern12: "a 'ga' h:mm")); CheckEqual("PM ga 1:05", ClockOf(format, OnePm, ClockFormat.Hours12)); CheckEqual("1:05", ClockOf(format, OnePm, ClockFormat.Hours12NoMarker)); } public void APrefixBeforeAMarkerThatIsFirst_ComesFirst() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(pattern12: "'Kl. 'a h:mm")); CheckEqual("Kl. PM 1:05", ClockOf(format, OnePm, ClockFormat.Hours12)); } public void TheSuffix_StaysWhenTheMarkerGoes() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(pattern12: "h:mm a'!'")); CheckEqual("1:05 PM!", ClockOf(format, OnePm, ClockFormat.Hours12)); CheckEqual("1:05!", ClockOf(format, OnePm, ClockFormat.Hours12NoMarker)); } public void APatternsHourPadding_IsKeptUnlessAsked() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(pattern24: "HH:mm")); var unset = new ClockFormat { Hours = ClockHours.TwentyFour }; var unpadded = new ClockFormat { Hours = ClockHours.TwentyFour, PadHour = ClockChoice.No }; CheckEqual("00:05", ClockOf(format, MidnightFive, unset)); CheckEqual("0:05", ClockOf(format, MidnightFive, unpadded)); } public void ATwelveHourPatternWithNoMarker_WritesOneAfterTheDigitsWhenAsked() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(pattern12: "h:mm")); CheckEqual("1:05 PM", ClockOf(format, OnePm, ClockFormat.Hours12)); } public void TheLongestPattern_FitsTheLongestLength() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns( pattern12WithSeconds: "'start 'hh:mm:ss' mid 'a' end'", pm: "pmpm")); var twelveWithSeconds = new ClockFormat { Hours = ClockHours.Twelve, Marker = ClockChoice.Yes, PadHour = ClockChoice.Yes, Seconds = true, }; CheckEqual("start 11:59:59 mid pmpm end", ClockOf(format, 23 * 3600 + 59 * 60 + 59, twelveWithSeconds)); } } public class WriteDurationPatternTests : TestFixture { public const long HourAndFiveMinutes = 3900; public void TextBeforeTheNumber_IsWrittenBeforeEachAmount() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(hour: "bkk{0}", minute: "a{0}")); CheckEqual("bkk1 a5", DurationOf(format, HourAndFiveMinutes)); } public void TextOnBothSidesOfTheNumber_IsWrittenAroundEachAmount() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(hour: "<{0}>", minute: "[{0}]")); CheckEqual("<1> [5]", DurationOf(format, HourAndFiveMinutes)); } public void APaddedAmount_PutsItsZeroAfterTheTextBeforeTheNumber() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(hour: "bkk{0}", minute: "a{0}")); var padded = new DurationFormat { Pad = DurationPad.Zero }; CheckEqual("bkk1 a05", DurationOf(format, HourAndFiveMinutes, padded)); } public void TheLongestDuration_FitsTheLongestLength() { NumberFormat format = WithTime(TimeNotationSamples.OfPatterns(day: "pppp{0}dddd", hour: "pppp{0}hhhh", minute: "pppp{0}mmmm", second: "pppp{0}ssss")); var everything = new DurationFormat { Largest = DurationUnit.Days, Smallest = DurationUnit.Seconds }; CheckTrue(DurationOf(format, long.MaxValue, everything).EndsWith("pppp7ssss")); } } public class ShortTierWriteTests : TestFixture { public static NumberFormat FormatOf(ShortNotation notation) { return new NumberFormat(",", 3, 3, "-", ".", "NaN", "Infinity", "e", notation); } public static ShortTier Tier(int shift, string pattern) { return new ShortTier(shift, UnitPattern.Parse(pattern)); } public static ShortNotation Of(ShortTier[] tiers, PluralRules plurals = null) { return new ShortNotation(3, tiers, plurals ?? PluralRules.None); } public void ATierWithNoText_WritesTheNumberOutAndKeepsItsWholePart() { ShortTier plain = Tier(0, "{0}"); ShortTier millions = Tier(6, "{0} Mio."); NumberFormat format = FormatOf(Of(new[] { plain, plain, plain, millions, millions, millions })); CheckEqual("1234", ShortOf(format, 1234, 3)); CheckEqual("123456", ShortOf(format, 123456, 3)); CheckEqual("1.23 Mio.", ShortOf(format, 1234567, 3)); } public void AShiftThatIsNotAMultipleOfThree_ChoosesTheWholePart() { ShortTier thousands = Tier(3, "{0} k"); ShortTier lakhs = Tier(5, "{0} L"); ShortTier crores = Tier(7, "{0} Cr"); NumberFormat format = FormatOf(Of(new[] { thousands, thousands, lakhs, lakhs, crores, crores })); CheckEqual("999", ShortOf(format, 999, 3)); CheckEqual("1.23 k", ShortOf(format, 1234, 3)); CheckEqual("12.3 k", ShortOf(format, 12345, 3)); CheckEqual("1.23 L", ShortOf(format, 123456, 3)); CheckEqual("12.3 L", ShortOf(format, 1234567, 3)); CheckEqual("1.23 Cr", ShortOf(format, 12345678, 3)); } public void MoreWholeDigitsThanTheSignificantOnes_AreNeverCutShort() { ShortTier thousands = Tier(3, "{0} mil"); ShortTier millions = Tier(6, "{0} M"); NumberFormat format = FormatOf(Of(new[] { thousands, thousands, thousands, millions, millions, millions, millions, millions, millions, })); CheckEqual("1235 M", ShortOf(format, 1234567890, 3)); CheckEqual("1.23 M", ShortOf(format, 1234567, 3)); } public void TextBeforeTheNumber_GoesAfterTheSign() { NumberFormat format = FormatOf(Of(new[] { Tier(3, "kt {0}") })); CheckEqual("kt 1.23", ShortOf(format, 1234, 3)); CheckEqual("-kt 1.23", ShortOf(format, -1234, 3)); } public void TextOnBothSidesOfTheNumber_IsWritten() { NumberFormat format = FormatOf(Of(new[] { Tier(3, "<{0}>") })); CheckEqual("<1.23>", ShortOf(format, 1234, 3)); } public void ThePluralFormFollowsTheNumberAsWritten() { var forms = new UnitPattern[6]; forms[(int)PluralCategory.One] = UnitPattern.Parse("{0} one"); forms[(int)PluralCategory.Few] = UnitPattern.Parse("{0} few"); forms[(int)PluralCategory.Many] = UnitPattern.Parse("{0} many"); forms[(int)PluralCategory.Other] = UnitPattern.Parse("{0} other"); NumberFormat format = FormatOf(Of(new[] { new ShortTier(0, forms) }, PluralRules.For("ru"))); CheckEqual("1001 one", ShortOf(format, 1001, 4)); CheckEqual("1002 few", ShortOf(format, 1002, 4)); CheckEqual("1005 many", ShortOf(format, 1005, 4)); CheckEqual("1001.5 other", ShortOf(format, 1001.5, 5)); } public void AShiftedNumber_IsPluralAsTheWholeNumberIs() { var forms = new UnitPattern[6]; forms[(int)PluralCategory.One] = UnitPattern.Parse("{0} one"); forms[(int)PluralCategory.Other] = UnitPattern.Parse("{0} other"); NumberFormat format = FormatOf(Of(new[] { new ShortTier(3, forms) }, PluralRules.For("en"))); CheckEqual("1 other", ShortOf(format, 1000, 1)); } public void PastTheLastTier_IsScientific() { NumberFormat format = FormatOf(Of(new[] { Tier(3, "{0}K"), Tier(3, "{0}K") })); CheckEqual("1.00K", ShortOf(format, 1000, 3)); CheckEqual("1.00e5", ShortOf(format, 1e5, 3)); CheckEqual("9.99K", ShortOf(format, 9990, 3)); } public void RoundingUp_CarriesIntoTheNextTier() { ShortTier thousands = Tier(3, "{0}k"); ShortTier millions = Tier(6, "{0}m"); NumberFormat format = FormatOf(Of(new[] { thousands, thousands, thousands, millions })); CheckEqual("999k", ShortOf(format, 999400, 3)); CheckEqual("1.00m", ShortOf(format, 999999, 3)); } public void ASignAfterText_GoesBetweenTheTextAndTheNumber() { var tier = new ShortTier(3, UnitPattern.Parse("kt {0}"), signAfterText: true); NumberFormat format = FormatOf(Of(new[] { tier })); CheckEqual("kt 1.23", ShortOf(format, 1234, 3)); CheckEqual("kt -1.23", ShortOf(format, -1234, 3)); } public void ASignAfterTextWithNoTextBefore_IsAheadOfTheNumber() { var tier = new ShortTier(3, UnitPattern.Parse("{0}K"), signAfterText: true); NumberFormat format = FormatOf(Of(new[] { tier })); CheckEqual("-1.23K", ShortOf(format, -1234, 3)); } public void TheLongestNumber_TakesExactlyTheMaxShortLength() { NumberFormat format = FormatOf(Of(new[] { Tier(0, "[[[{0}]]]") })); CheckEqual("-[[[1234.00000000000]]]", ShortOf(format, -1234, NumberFormat.MaxSignificantDigits)); CheckEqual(23, format.MaxShortLength); } } public class LocaleShortTests : TestFixture { public static string ShortIn(string tag, double value, int digits) { return ShortOf(NumberFormat.For(tag), value, digits); } public void English_WritesKMBT() { CheckEqual("1.23K", ShortIn("en", 1234, 3)); CheckEqual("1.23M", ShortIn("en", 1234567, 3)); CheckEqual("1.23T", ShortIn("en", 1.234e12, 3)); } public void French_SeparatesTheSuffixWithANoBreakSpace() { CheckEqual("1,23" + (char)0xA0 + "k", ShortIn("fr", 1234, 3)); CheckEqual("1,23" + (char)0xA0 + "M", ShortIn("fr", 1234567, 3)); } public void German_WritesNoSuffixForTheThousands() { CheckEqual("1234", ShortIn("de", 1234, 3)); CheckEqual("123457", ShortIn("de", 123456.7, 3)); CheckEqual("1,23" + (char)0xA0 + "Mio.", ShortIn("de", 1234567, 3)); CheckEqual("1,23" + (char)0xA0 + "Mrd.", ShortIn("de", 1.234e9, 3)); } public void Spanish_KeepsFourWholeDigitsForTheBillions() { CheckEqual("1,23" + (char)0xA0 + "mil", ShortIn("es", 1234, 3)); CheckEqual("1235" + (char)0xA0 + "M", ShortIn("es", 1234567890, 3)); } public void Japanese_GroupsByTenThousands() { string tenThousand = LocaleTimeTests.Text(0x4E07); string hundredMillion = LocaleTimeTests.Text(0x5104); CheckEqual("1234", ShortIn("ja", 1234, 3)); CheckEqual("1.23" + tenThousand, ShortIn("ja", 12345, 3)); CheckEqual("123" + tenThousand, ShortIn("ja", 1234567, 3)); CheckEqual("12.3" + hundredMillion, ShortIn("ja", 1.234e9, 3)); } public void Hindi_GroupsByLakhs() { string lakh = LocaleTimeTests.Text(0x932, 0x93E, 0x916); CheckEqual("1.23" + (char)0xA0 + lakh, ShortIn("hi", 123456, 3)); CheckEqual("12.3" + (char)0xA0 + lakh, ShortIn("hi", 1234567, 3)); } public void Swahili_WritesTheThousandsBeforeTheNumberWithTheMinusInside() { string elfu = "elfu" + (char)0xA0; CheckEqual(elfu + "1.23", ShortIn("sw", 1234, 3)); CheckEqual(elfu + "-1.23", ShortIn("sw", -1234, 3)); CheckEqual("-12.3M", ShortIn("sw", -12345678, 3)); } public void Arabic_WritesADifferentThousandsWordForFew() { string few = LocaleTimeTests.Text(0x622, 0x644, 0x627, 0x641); string other = LocaleTimeTests.Text(0x623, 0x644, 0x641); CheckTrue(ShortIn("ar-AE", 1003, 4).EndsWith(few)); CheckTrue(ShortIn("ar-AE", 5000, 1).EndsWith(other)); } public void EveryLocale_WritesLargeAndSmallNumbersWithinItsMaxShortLength() { double[] values = { 0, 0.5, 1234, 99999.9, 12345678, 1e14, 1e19, -9.999999e18, 1e300 }; foreach (string tag in NumberFormat.LocaleTags()) { NumberFormat format = NumberFormat.For(tag); foreach (double value in values) { ShortOf(format, value, 1); ShortOf(format, value, NumberFormat.MaxSignificantDigits); } } } } public class LocaleTimeTests : TestFixture { public const long OnePm = 13 * 3600 + 5 * 60; public const long OnePmAndSevenSeconds = OnePm + 7; public const long MidnightFive = 5 * 60; public const long NoonFive = 12 * 3600 + 5 * 60; public const long HourAndFiveMinutes = 3900; public static readonly ClockFormat Hours24WithSeconds = new ClockFormat { Hours = ClockHours.TwentyFour, PadHour = ClockChoice.Yes, Seconds = true, }; public static readonly ClockFormat Hours12WithSeconds = new ClockFormat { Hours = ClockHours.Twelve, Marker = ClockChoice.Yes, Seconds = true, }; public static string Text(params int[] codePoints) { string returnMe = ""; foreach (int codePoint in codePoints) { returnMe += char.ConvertFromUtf32(codePoint); } return returnMe; } public static string ClockIn(string tag, long seconds, ClockFormat clock = default) { return ClockOf(NumberFormat.For(tag), seconds, clock); } public static string DurationIn(string tag, long seconds) { return DurationOf(NumberFormat.For(tag), seconds); } public void French_WritesTwentyFourHoursUnlessAsked() { CheckEqual("13:05", ClockIn("fr", OnePm)); CheckEqual("05:07", ClockIn("fr", 5 * 3600 + 7 * 60)); CheckEqual("1:05" + (char)0x202F + "PM", ClockIn("fr", OnePm, ClockFormat.Hours12)); } public void English_WritesTwelveHoursWithANarrowNoBreakSpaceBeforeTheMarker() { CheckEqual("1:05" + (char)0x202F + "PM", ClockIn("en", OnePm)); CheckEqual("12:05" + (char)0x202F + "AM", ClockIn("en", MidnightFive)); } public void BritishEnglish_WritesTwentyFourHoursAndLowerCaseMarkers() { CheckEqual("13:05", ClockIn("en-GB", OnePm)); CheckEqual("1:05" + (char)0x202F + "pm", ClockIn("en-GB", OnePm, ClockFormat.Hours12)); } public void Finnish_SeparatesTheClockWithPeriods() { CheckEqual("13.05", ClockIn("fi", OnePm)); CheckEqual("13.05.07", ClockIn("fi", OnePmAndSevenSeconds, Hours24WithSeconds)); } public void Korean_WritesTheMarkerFirstWithAGap() { string afternoon = Text(0xC624, 0xD6C4); string morning = Text(0xC624, 0xC804); CheckEqual(afternoon + " 1:05", ClockIn("ko", OnePm)); CheckEqual(morning + " 12:05", ClockIn("ko", MidnightFive)); } public void Japanese_CountsTwelveHoursFromZero() { string afternoon = Text(0x5348, 0x5F8C); string morning = Text(0x5348, 0x524D); CheckEqual(morning + "0:05", ClockIn("ja", MidnightFive, ClockFormat.Hours12)); CheckEqual(afternoon + "0:05", ClockIn("ja", NoonFive, ClockFormat.Hours12)); CheckEqual(afternoon + "1:05", ClockIn("ja", OnePm, ClockFormat.Hours12)); } public void Japanese_WritesDurationsInTheShortUnits() { string hours = " " + Text(0x6642, 0x9593); string minutes = " " + Text(0x5206); CheckEqual("1" + hours + "5" + minutes, DurationIn("ja", HourAndFiveMinutes)); } public void TraditionalChinese_WritesAFlexibleDayPeriodAsTheMarker() { CheckEqual(Text(0x4E0B, 0x5348) + "1:05", ClockIn("zh-Hant", OnePm)); } public void Thai_WritesATextAfterTheTwentyFourHourClock() { CheckEqual("13:05 " + Text(0x0E19) + ".", ClockIn("th", OnePm)); } public void LowGerman_WritesATextBeforeTheClock() { CheckEqual("Kl. 13.05", ClockIn("nds", OnePm)); CheckEqual("Kl. 1.05" + (char)0x202F + "PM", ClockIn("nds", OnePm, ClockFormat.Hours12)); } public void TokiPona_WritesASignBeforeTheClock() { CheckEqual("#13:05", ClockIn("tok", OnePm)); } public void CanadianFrench_SeparatesTheFieldsWithWords() { CheckEqual("13 h 05", ClockIn("fr-CA", OnePm)); CheckEqual("13 h 05 min 07 s", ClockIn("fr-CA", OnePmAndSevenSeconds, Hours24WithSeconds)); CheckEqual("1 h 05 min 07 s p.m.", ClockIn("fr-CA", OnePmAndSevenSeconds, Hours12WithSeconds)); } public void Occitan_WritesATextAfterTheSeconds() { CheckEqual("13h05 07 seg.", ClockIn("oc", OnePmAndSevenSeconds, Hours24WithSeconds)); } public void Bulgarian_WritesATextAfterTheClock() { CheckEqual("13:05 " + Text(0x0447) + ".", ClockIn("bg", OnePm)); } public void Swahili_WritesTheUnitBeforeTheNumber() { CheckEqual("saa 1 na dak 5", DurationIn("sw", HourAndFiveMinutes)); } public void German_WritesDurationsWithItsOwnUnits() { CheckEqual("1h, 5 Min.", DurationIn("de", HourAndFiveMinutes)); } public void EveryLocale_WritesAClockAndADurationWithinTheirMaxLengths() { var longest = new ClockFormat { Hours = ClockHours.Twelve, Marker = ClockChoice.Yes, PadHour = ClockChoice.Yes, Seconds = true, }; var everything = new DurationFormat { Largest = DurationUnit.Days, Smallest = DurationUnit.Seconds }; foreach (string tag in NumberFormat.LocaleTags()) { NumberFormat format = NumberFormat.For(tag); var clockBuffer = new char[format.MaxClockLength]; var durationBuffer = new char[format.MaxDurationLength]; format.WriteClock(23 * 3600 + 59 * 60 + 59, longest, clockBuffer, 0); format.WriteClock(23 * 3600 + 59 * 60 + 59, Hours24WithSeconds, clockBuffer, 0); format.WriteDuration(long.MaxValue, everything, durationBuffer, 0); } } } public class WriterBufferTests : TestFixture { public delegate int Writer(CharView destination); public static string WrittenInto(int length, Writer write) { var buffer = new char[length]; return new string(buffer, 0, write(new CharView(buffer))); } public void Count_ARoomTheLengthOfTheTextExactly_Fits() { CheckEqual("1,234", WrittenInto(5, to => NumberFormat.Invariant.WriteCount(1234, to, 0))); } public void Count_OneCharacterShort_Throws() { CheckThrow(typeof(ArgumentException)); WrittenInto(4, to => NumberFormat.Invariant.WriteCount(1234, to, 0)); } public void Fixed_ARoomTheLengthOfTheTextExactly_Fits() { CheckEqual("1,234.50", WrittenInto(8, to => NumberFormat.Invariant.WriteFixed(1234.5, 2, to, 0))); } public void Fixed_OneCharacterShort_Throws() { CheckThrow(typeof(ArgumentException)); WrittenInto(7, to => NumberFormat.Invariant.WriteFixed(1234.5, 2, to, 0)); } public void Decimal_ARoomTheLengthOfTheTextExactly_Fits() { CheckEqual("1,234.50", WrittenInto(8, to => NumberFormat.Invariant.WriteDecimal(1234.5m, 2, to, 0))); } public void Decimal_OneCharacterShort_Throws() { CheckThrow(typeof(ArgumentException)); WrittenInto(7, to => NumberFormat.Invariant.WriteDecimal(1234.5m, 2, to, 0)); } public void DecimalUngrouped_ARoomTheLengthOfTheTextExactly_Fits() { CheckEqual("1234.50", WrittenInto(7, to => NumberFormat.Invariant.WriteDecimalUngrouped(1234.5m, 2, to, 0))); } public void DecimalUngrouped_OneCharacterShort_Throws() { CheckThrow(typeof(ArgumentException)); WrittenInto(6, to => NumberFormat.Invariant.WriteDecimalUngrouped(1234.5m, 2, to, 0)); } public void Scientific_ARoomTheLengthOfTheTextExactly_Fits() { CheckEqual("1.23e4", WrittenInto(6, to => NumberFormat.Invariant.WriteScientific(12345, 3, to, 0))); } public void Scientific_OneCharacterShort_Throws() { CheckThrow(typeof(ArgumentException)); WrittenInto(5, to => NumberFormat.Invariant.WriteScientific(12345, 3, to, 0)); } public void ShortExponent_ARoomTheLengthOfTheTextExactly_Fits() { CheckEqual("1.2K", WrittenInto(4, to => NumberFormat.Invariant.WriteShortExponent(1234, 2, to, 0))); } public void ShortExponent_OneCharacterShort_Throws() { CheckThrow(typeof(ArgumentException)); WrittenInto(3, to => NumberFormat.Invariant.WriteShortExponent(1234, 2, to, 0)); } public void Percent_ARoomTheLengthOfTheTextExactly_Fits() { CheckEqual("50%", WrittenInto(3, to => NumberFormat.Invariant.WritePercent(0.5, 0, to, 0))); } public void Percent_OneCharacterShort_Throws() { CheckThrow(typeof(ArgumentException)); WrittenInto(2, to => NumberFormat.Invariant.WritePercent(0.5, 0, to, 0)); } public void Clock_ARoomTheLengthOfTheTextExactly_Fits() { CheckEqual("1:05 PM", WrittenInto(7, to => NumberFormat.Invariant.WriteClock(13 * 3600 + 5 * 60, default, to, 0))); } public void Clock_OneCharacterShort_Throws() { CheckThrow(typeof(ArgumentException)); WrittenInto(6, to => NumberFormat.Invariant.WriteClock(13 * 3600 + 5 * 60, default, to, 0)); } public void Duration_ARoomTheLengthOfTheTextExactly_Fits() { CheckEqual("1h 5m", WrittenInto(5, to => NumberFormat.Invariant.WriteDuration(3900, default, to, 0))); } public void Duration_OneCharacterShort_Throws() { CheckThrow(typeof(ArgumentException)); WrittenInto(4, to => NumberFormat.Invariant.WriteDuration(3900, default, to, 0)); } public void NotANumber_ARoomTheLengthOfTheTextExactly_Fits() { CheckEqual("NaN", WrittenInto(3, to => NumberFormat.Invariant.WriteNotANumber(to, 0))); } public void NotANumber_OneCharacterShort_Throws() { CheckThrow(typeof(ArgumentException)); WrittenInto(2, to => NumberFormat.Invariant.WriteNotANumber(to, 0)); } public void Infinity_ARoomTheLengthOfTheTextExactly_Fits() { CheckEqual("-Infinity", WrittenInto(9, to => NumberFormat.Invariant.WriteInfinity(true, to, 0))); } public void Infinity_OneCharacterShort_Throws() { CheckThrow(typeof(ArgumentException)); WrittenInto(8, to => NumberFormat.Invariant.WriteInfinity(true, to, 0)); } public void ARoomLeftAfterThePositionThatIsTooShort_Throws() { CheckThrow(typeof(ArgumentException)); WrittenInto(8, to => NumberFormat.Invariant.WriteCount(1234, to, 4)); } public static string LeftBy(int length, Writer write) { var buffer = new char[length]; for (int i = 0; i < length; ++i) { buffer[i] = '#'; } try { write(new CharView(buffer)); } catch (ArgumentException) { } return new string(buffer); } public void Count_OneCharacterShort_LeavesTheBufferAsItWas() { CheckEqual("####", LeftBy(4, to => NumberFormat.Invariant.WriteCount(1234, to, 0))); } public void Fixed_OneCharacterShort_LeavesTheBufferAsItWas() { CheckEqual("#######", LeftBy(7, to => NumberFormat.Invariant.WriteFixed(1234.5, 2, to, 0))); } public void Fixed_ShortAfterAPosition_LeavesTheBufferAsItWas() { CheckEqual("######", LeftBy(6, to => NumberFormat.Invariant.WriteFixed(12.5, 2, to, 2))); } public void Decimal_OneCharacterShort_LeavesTheBufferAsItWas() { CheckEqual("#######", LeftBy(7, to => NumberFormat.Invariant.WriteDecimal(1234.5m, 2, to, 0))); } public void DecimalUngrouped_OneCharacterShort_LeavesTheBufferAsItWas() { CheckEqual("######", LeftBy(6, to => NumberFormat.Invariant.WriteDecimalUngrouped(1234.5m, 2, to, 0))); } public void Scientific_OneCharacterShort_LeavesTheBufferAsItWas() { CheckEqual("#####", LeftBy(5, to => NumberFormat.Invariant.WriteScientific(12345, 3, to, 0))); } public void ShortExponent_OneCharacterShort_LeavesTheBufferAsItWas() { CheckEqual("###", LeftBy(3, to => NumberFormat.Invariant.WriteShortExponent(1234, 2, to, 0))); } public void ShortExponentWrittenInScientific_OneCharacterShort_LeavesTheBufferAsItWas() { CheckEqual("#####", LeftBy(5, to => NumberFormat.Invariant.WriteShortExponent(1.5e30, 3, to, 0))); } public void Percent_OneCharacterShort_LeavesTheBufferAsItWas() { CheckEqual("##", LeftBy(2, to => NumberFormat.Invariant.WritePercent(0.5, 0, to, 0))); } public void Clock_OneCharacterShort_LeavesTheBufferAsItWas() { CheckEqual("######", LeftBy(6, to => NumberFormat.Invariant.WriteClock(13 * 3600 + 5 * 60, default, to, 0))); } public void Duration_OneCharacterShort_LeavesTheBufferAsItWas() { CheckEqual("####", LeftBy(4, to => NumberFormat.Invariant.WriteDuration(3900, default, to, 0))); } public void Duration_AnInvalidFormat_LeavesTheBufferAsItWas() { var backwards = new DurationFormat { Largest = DurationUnit.Seconds, Smallest = DurationUnit.Days }; CheckEqual("#####", LeftBy(5, to => NumberFormat.Invariant.WriteDuration(3900, backwards, to, 0))); } } public class TryParseTests : TestFixture { public static readonly NumberFormat German = NumberFormat.For("de-DE"); public static readonly NumberFormat English = NumberFormat.For("en-US"); public const NumberStyles Usual = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint; [IgnoreTest] public void CheckReads(decimal expected, string text, NumberFormat format, NumberStyles styles = Usual) { CheckTrue(format.TryParse(text, styles, out decimal parsed)); CheckEqual(expected, parsed); } [IgnoreTest] public void CheckRefuses(string text, NumberFormat format, NumberStyles styles = Usual) { CheckFalse(format.TryParse(text, styles, out decimal parsed)); CheckEqual(0m, parsed); } public void PlainDigits_AreRead() { CheckReads(42m, "42", English); } public void ADecimalPoint_IsRead() { CheckReads(-3.5m, "-3.5", English); } public void APlusSign_IsRead() { CheckReads(7m, "+7", English); } public void SurroundingWhitespace_IsIgnored() { CheckReads(12m, " 12 \t", English); } public void ArabicIndicDigits_AreRead() { CheckReads(34m, ((char)0x0663).ToString() + (char)0x0664, English); } public void FullWidthDigits_AreRead() { CheckReads(5.5m, ((char)0xFF15).ToString() + "." + (char)0xFF15, English); } public void DigitsOfDifferentScripts_AreReadTogether() { CheckReads(-12m, "-1" + (char)0x0662, English); } public void AUnicodeMinusSign_IsRead() { CheckReads(-5m, ((char)0x2212) + "5", English); } public void AnExponent_IsReadWhenAllowed() { CheckReads(1000m, "1e3", English, Usual | NumberStyles.AllowExponent); } public void AnExponent_IsRefusedWhenNotAllowed() { CheckRefuses("1e3", English); } public void ASign_IsRefusedWhenNotAllowed() { CheckRefuses("-5", English, NumberStyles.AllowDecimalPoint); CheckRefuses("+5", English, NumberStyles.AllowDecimalPoint); CheckRefuses(((char)0x2212) + "5", English, NumberStyles.AllowDecimalPoint); } public void ADecimalPoint_IsRefusedWhenNotAllowed() { CheckRefuses("1.5", English, NumberStyles.AllowLeadingSign); CheckRefuses("1,5", German, NumberStyles.AllowLeadingSign); } public void WithNothingAllowed_PlainDigitsAreStillRead() { CheckReads(15m, "15", English, NumberStyles.None); } public void ThousandsAllowed_AGroupSeparatorIsRead() { CheckReads(1234.5m, "1,234.5", English, Usual | NumberStyles.AllowThousands); } public void TheCulturesDecimalComma_IsRead() { CheckReads(1.5m, "1,5", German); } public void APeriodInACultureWithADecimalComma_IsReadAsADecimalPoint() { CheckReads(1.5m, "1.5", German); } public void ALoneCommaInACultureWithADecimalPoint_IsRefused() { CheckRefuses("1,5", English); CheckRefuses("1,300", English); } public void AGroupSeparator_IsRefused() { CheckRefuses("1,234.5", English); } public void APeriodInACultureWithADecimalComma_IsReadAsADecimalPointEvenWithThreeDigits() { CheckReads(1.5m, "1.500", German); } public void SeveralCommas_AreRefused() { CheckRefuses("1,2,3", English); } public void ACommaAndAPeriodTogether_AreRefused() { CheckRefuses("1.234,5", English); } public void Nothing_IsRefused() { CheckRefuses("", English); CheckRefuses(" ", English); CheckFalse(English.TryParse(null, Usual, out _)); } public void Words_AreRefused() { CheckRefuses("abc", English); CheckRefuses("12abc", English); } public void AnUnfinishedNumber_IsRefused() { CheckRefuses("-", English); CheckRefuses(".", English); CheckRefuses("1e", English); } public void ANumberTooBigForADecimal_IsRefused() { CheckRefuses("99999999999999999999999999999999", English); } public void ADigitOfAnotherScriptPastTheBasicPlane_IsRead() { string text = char.ConvertFromUtf32(0x1D7CF) + char.ConvertFromUtf32(0x1D7D0); CheckReads(12m, text, English); } public void DirectionMarks_AreIgnored() { CheckReads(-12m, ((char)0x200F).ToString() + "-" + (char)0x200E + "12", English); CheckReads(7m, ((char)0x061C).ToString() + "7", English); } public void TheFormatsOwnDecimalSeparator_IsRead() { CheckReads(1.5m, "15", WithSymbols(group: ",", decimalSeparator: "", exponent: "e")); } public void TheFormatsOwnExponentSymbol_IsReadWhenAllowed() { NumberFormat format = WithSymbols(group: ",", decimalSeparator: ".", exponent: "x10^"); CheckReads(1000m, "1x10^3", format, Usual | NumberStyles.AllowExponent); CheckRefuses("1x10^3", format); } public void ADecimalSeparatorOfOtherScripts_IsRead() { CheckReads(1.5m, "1" + (char)0x066B + "5", NumberFormat.For("ar-EG")); } public void ThousandsAllowed_TheFormatsOwnGroupSeparatorIsRead() { CheckReads(1234.5m, "1.234,5", German, Usual | NumberStyles.AllowThousands); CheckReads(1234m, "1" + (char)0x066C + "234", NumberFormat.For("ar-EG"), Usual | NumberStyles.AllowThousands); } public void ThousandsAllowed_APeriodInAGroupingByPeriodsFormatIsAGroupSeparator() { CheckReads(15m, "1.5", German, Usual | NumberStyles.AllowThousands); } public void ThousandsAllowed_AnOrdinarySpaceStandsForASpaceSeparator() { NumberFormat french = NumberFormat.For("fr-FR"); CheckReads(1234.5m, "1 234,5", french, Usual | NumberStyles.AllowThousands); CheckReads(1234.5m, "1" + (char)0xA0 + "234,5", french, Usual | NumberStyles.AllowThousands); CheckReads(1234.5m, "1" + (char)0x202F + "234,5", french, Usual | NumberStyles.AllowThousands); } public void ThousandsAllowed_AnAsciiApostropheStandsForATypographicOne() { CheckReads(1234m, "1'234", NumberFormat.For("de-CH"), Usual | NumberStyles.AllowThousands); } public void ThousandsNotAllowed_AGroupSeparatorIsRefused() { CheckRefuses("1 234", NumberFormat.For("fr-FR")); CheckRefuses("1" + (char)0x066C + "234", NumberFormat.For("ar-EG")); } public void ASpaceInAFormatThatGroupsWithAComma_IsRefused() { CheckRefuses("1 234", English, Usual | NumberStyles.AllowThousands); } public void ATypedMinusSign_IsReadInAFormatThatWritesAnother() { CheckReads(-5m, "-5", NumberFormat.For("sv-SE")); CheckReads(-5m, ((char)0x2212).ToString() + "5", NumberFormat.For("sv-SE")); } } public class WriteDecimalTests : TestFixture { public void WholeAndFractionalDigits_AreWritten() { CheckEqual("1,234.50", DecimalOf(NumberFormat.Invariant, 1234.5m, 2)); } public void ADecimalRoundsHalfAwayFromZero() { CheckEqual("0.13", DecimalOf(NumberFormat.Invariant, 0.125m, 2)); CheckEqual("-0.13", DecimalOf(NumberFormat.Invariant, -0.125m, 2)); } public void NoDecimals_WritesNoSeparator() { CheckEqual("3", DecimalOf(NumberFormat.Invariant, 2.5m, 0)); } public void TheFormatsDigitsAndSymbols_AreUsed() { string expected = new string(new[] { (char)0x0661, (char)0x066C, (char)0x0662, (char)0x0663, (char)0x0664, (char)0x066B, (char)0x0665, }); CheckEqual(expected, DecimalOf(NumberFormat.For("ar-EG"), 1234.5m, 1)); } public void TheLargestDecimal_IsWrittenExactly() { CheckEqual("79,228,162,514,264,337,593,543,950,335", DecimalOf(NumberFormat.Invariant, decimal.MaxValue, 0)); } public void ADecimalWithAMoreExactValueThanADoubleHolds_IsWrittenExactly() { CheckEqual("0.123456789", DecimalOf(NumberFormat.Invariant, 0.123456789m, 9)); CheckEqual("12,345,678,901,234.5678", DecimalOf(NumberFormat.Invariant, 12345678901234.5678m, 4)); } public void TooManyDecimals_Throw() { CheckThrow(typeof(ArgumentOutOfRangeException)); DecimalOf(NumberFormat.Invariant, 1m, NumberFormat.MaxDecimals + 1); } public void NegativeDecimals_Throw() { CheckThrow(typeof(ArgumentOutOfRangeException)); DecimalOf(NumberFormat.Invariant, 1m, -1); } public void TheBufferNeededNeverExceedsMaxFixedLength() { NumberFormat french = NumberFormat.For("fr-FR"); string written = DecimalOf(french, -decimal.MaxValue, NumberFormat.MaxDecimals); CheckTrue(written.Length <= french.MaxFixedLength); } } public class ToStringFixedTests : TestFixture { public void Grouped_GroupsTheWholePart() { CheckEqual("1,234.50", NumberFormat.Invariant.ToStringFixed(1234.5m, 2, grouped: true)); } public void Ungrouped_LeavesTheWholePartWhole() { CheckEqual("1234.50", NumberFormat.Invariant.ToStringFixed(1234.5m, 2, grouped: false)); } public void TooManyDecimals_Throw() { CheckThrow(typeof(ArgumentOutOfRangeException)); NumberFormat.Invariant.ToStringFixed(1m, NumberFormat.MaxDecimals + 1, grouped: false); } } public class WriteDecimalUngroupedTests : TestFixture { public void TheWholePart_HasNoGroupSeparators() { CheckEqual("1234567.25", UngroupedOf(NumberFormat.Invariant, 1234567.25m, 2)); } public void ANegativeNumber_KeepsItsSign() { CheckEqual("-1234.5", UngroupedOf(NumberFormat.Invariant, -1234.5m, 1)); } public void ADecimalSeparator_IsTheFormats() { CheckEqual("1234,5", UngroupedOf(NumberFormat.For("de-DE"), 1234.5m, 1)); } public void ALargeNumber_HasNoGroupSeparators() { CheckEqual("79228162514264337593543950335", UngroupedOf(NumberFormat.Invariant, decimal.MaxValue, 0)); } public void TooManyDecimals_Throw() { CheckThrow(typeof(ArgumentOutOfRangeException)); UngroupedOf(NumberFormat.Invariant, 1m, NumberFormat.MaxDecimals + 1); } public void WhatIsWritten_IsReadBackExactly() { NumberFormat french = NumberFormat.For("fr-FR"); CheckTrue(french.TryParse(UngroupedOf(french, -1234.56m, 2), NumberStyles.Float, out decimal parsed)); CheckEqual(-1234.56m, parsed); } } } }