diff --git a/src/Humanizer/MetricNumeralExtensions.cs b/src/Humanizer/MetricNumeralExtensions.cs index 46462ea92..6c47a1f17 100644 --- a/src/Humanizer/MetricNumeralExtensions.cs +++ b/src/Humanizer/MetricNumeralExtensions.cs @@ -391,6 +391,16 @@ static string BuildRepresentation(double input, MetricNumeralFormats? formats, i return BuildMetricRepresentation(input, exponent, formats, decimals); } + if (decimals.HasValue) + { + var rounded = Math.Round(input, decimals.Value); + if (!rounded.Equals(0d)) + { + var roundedExponent = (int)Math.Floor(Math.Log10(Math.Abs(rounded)) / 3); + if (!roundedExponent.Equals(0)) + return BuildMetricRepresentation(rounded, roundedExponent, formats, decimals); + } + } var representation = decimals.HasValue ? Math .Round(input, decimals.Value) diff --git a/tests/Humanizer.Tests/MetricNumeralTests.cs b/tests/Humanizer.Tests/MetricNumeralTests.cs index c6a43fad3..21f3a4561 100644 --- a/tests/Humanizer.Tests/MetricNumeralTests.cs +++ b/tests/Humanizer.Tests/MetricNumeralTests.cs @@ -202,6 +202,11 @@ public void TestAllSymbolsAsLong(long subject, int? decimals, string expected) = [InlineData("1 milli", 1E-3, MetricNumeralFormats.WithSpace | MetricNumeralFormats.UseName, null)] [InlineData("1 thousandth", 1E-3, MetricNumeralFormats.WithSpace | MetricNumeralFormats.UseShortScaleWord, null)] [InlineData("1 thousandth", 1E-3, MetricNumeralFormats.WithSpace | MetricNumeralFormats.UseLongScaleWord, null)] + [InlineData("1k", 999.9, null, 0)] + [InlineData("-1k", -999.9, null, 0)] + [InlineData("1k", 999.99, null, 1)] + [InlineData("1M", 999949.9, null, 0)] + [InlineData("999", 999.4, null, 0)] public void ToMetric(string expected, double input, MetricNumeralFormats? format, int? decimals) => Assert.Equal(expected, input.ToMetric(format, decimals));