Skip to content

Commit 29ff35e

Browse files
committed
[GH Usage] Simplified ToKiloFormat
1 parent 587a15f commit 29ff35e

2 files changed

Lines changed: 13 additions & 21 deletions

File tree

src/NuGetGallery/Extensions/NumberExtensions.cs

Lines changed: 12 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -76,36 +76,28 @@ public static string ToUserFriendlyBytesLabel(this long bytes)
7676
/// <returns>String representation of the formatted number</returns>
7777
public static string ToKiloFormat(this int number)
7878
{
79-
bool isNegative = number < 0;
80-
if (isNegative)
79+
// To avoid overflow (with Math.Abs()). 1 difference won't make a difference in the simplified format :)
80+
if (number == int.MinValue)
8181
{
82-
number *= -1;
82+
number = -1 * int.MaxValue;
8383
}
8484

85-
if (number < 1000)
85+
if (Math.Abs(number) < 1000)
8686
{
87-
return (isNegative ? "-" : "") + number.ToString();
87+
return number.ToString();
8888
}
8989

9090
var powers = new[]
9191
{
92-
new { Pow = 9 , Value = 1_000_000_000f, Unit = 'B'},
93-
new { Pow = 6 , Value = 1_000_000f , Unit = 'M'},
94-
new { Pow = 3 , Value = 1_000f , Unit = 'K'},
95-
new { Pow = 0 , Value = 1f , Unit = '\0'}
92+
new { Value = 1_000_000_000f, Unit = 'B'},
93+
new { Value = 1_000_000f , Unit = 'M'},
94+
new { Value = 1_000f , Unit = 'K'}
9695
};
9796

98-
var multiplier = powers.First(x => number.ToString().Length > x.Pow);
99-
var simplifiedNumber = (number / multiplier.Value);
100-
var roundValue = (int)float.Parse(string.Format("{0:F1}", simplifiedNumber));
101-
102-
// This is used in some cases to get the right power with its unit (e.g: 999_999_000 is rounded to 1.0B)
103-
if (roundValue > simplifiedNumber)
104-
{
105-
return (roundValue * (int)multiplier.Value * (isNegative ? -1 : 1)).ToKiloFormat();
106-
}
107-
108-
return (isNegative ? "-" : "") + string.Format("{0:F1}", simplifiedNumber) + multiplier.Unit;
97+
return powers
98+
.Where(pow => Math.Abs(Math.Round(number / pow.Value, 3)) >= 1f)
99+
.Select(pow => string.Format("{0:F1}{1}", number / pow.Value, pow.Unit))
100+
.First();
109101
}
110102
}
111103
}

src/NuGetGallery/Services/IFeatureFlagService.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ public interface IFeatureFlagService
5757
/// Whether a user can see the "GitHub Usage" section in a package's display page as well
5858
/// as the added "GitHub Usage count" in the "Statistics" section
5959
/// </summary>
60-
/// <param name="user">The user to test fot the Flight</param>
60+
/// <param name="user">The user to test for the Flight</param>
6161
/// <returns>Whether or not the Flight is enabled for the user</returns>
6262
bool IsGitHubUsageEnabled(User user);
6363
}

0 commit comments

Comments
 (0)