Skip to content

Commit e680da0

Browse files
committed
[GH Usage] Simplified ToKiloFormat
1 parent f3b3dcd commit e680da0

1 file changed

Lines changed: 14 additions & 23 deletions

File tree

src/NuGetGallery/Extensions/NumberExtensions.cs

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System;
55
using System.Globalization;
6+
using System.Linq;
67
using System.Text;
78

89
namespace NuGetGallery
@@ -75,32 +76,22 @@ public static string ToUserFriendlyBytesLabel(this long bytes)
7576
/// <returns></returns>
7677
public static string ToKiloFormat(this int number)
7778
{
78-
if (number >= 1_000_000_000)
79+
var thresholds = new[]
7980
{
80-
return new StringBuilder((number / 1_000_000_000.0f).ToString("F3")) { [4] = 'B' }.ToString();
81-
}
82-
83-
if (number >= 100_000_000)
84-
{
85-
return (number / 1_000_000) + "M";
86-
}
87-
88-
if (number >= 1_000_000)
89-
{
90-
return new StringBuilder((number / 1_000_000.0f).ToString(number >= 10_000_000 ? "F2" : "F3")) { [4] = 'M' }.ToString();
91-
}
92-
93-
if (number >= 100_000)
94-
{
95-
return (number / 1_000) + "K";
96-
}
81+
new { Threshold = 1_000_000_000, Transform = new Func<int, float>((x) => x / 1_000_000_000f), Format = "{0:F3}B", Trim = true },
82+
new { Threshold = 100_000_000, Transform = new Func<int, float>((x) => x / 1_000_000), Format = "{0:F0}M", Trim = false},
83+
new { Threshold = 10_000_000, Transform = new Func<int, float>((x) => x / 1_000_000f), Format = "{0:F2}M", Trim = true},
84+
new { Threshold = 1_000_000, Transform = new Func<int, float>((x) => x / 1_000_000f), Format = "{0:F3}M", Trim = true},
85+
new { Threshold = 100_000, Transform = new Func<int, float>((x) => x / 1_000), Format = "{0}K", Trim = false},
86+
new { Threshold = 10_000, Transform = new Func<int, float>((x) => x / 1_000f), Format = "{0:F2}K", Trim = true},
87+
new { Threshold = 1_000, Transform = new Func<int, float>((x) => x / 1_000f), Format = "{0:F3}K", Trim = true},
88+
new { Threshold = int.MinValue, Transform = new Func<int, float>((x) => x), Format = "{0}", Trim = false}
89+
};
9790

98-
if (number >= 1000)
99-
{
100-
return new StringBuilder((number / 1_000.0f).ToString(number >= 10_000 ? "F2" : "F3")) { [4] = 'K' }.ToString();
101-
}
91+
var elem = thresholds.First(d => number >= d.Threshold);
92+
var strFormat = string.Format(elem.Format, elem.Transform(number));
10293

103-
return number.ToString("#,0");
94+
return elem.Trim ? strFormat.Remove(4, 1) : strFormat;
10495
}
10596
}
10697
}

0 commit comments

Comments
 (0)