Skip to content

Commit e8acf7d

Browse files
committed
Force a number of significant figures in Y axis values
1 parent e805b73 commit e8acf7d

1 file changed

Lines changed: 20 additions & 5 deletions

File tree

src/NuGetGallery/ViewModels/StatisticsPackagesViewModel.cs

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -142,22 +142,37 @@ public string DisplayPercentage(float amount, float total)
142142
return (amount / total).ToString("P0", CultureInfo.CurrentCulture);
143143
}
144144

145-
public string DisplayShortNumber(long number)
145+
public string DisplayShortNumber(double number, int sigFigures = 3)
146146
{
147147
var numDiv = 0;
148148

149149
while (number >= 1000)
150150
{
151-
number = number / 1000;
151+
number /= 1000;
152152
numDiv++;
153153
}
154154

155-
if (numDiv >= _magnitudeAbbreviations.Length)
155+
// Find a rounding factor based on size, and round to sigFigures, e.g. for 3 sig figs, 1.774545 becomes 1.77.
156+
var placeValues = Math.Ceiling(Math.Log10(number));
157+
var roundingFactor = Math.Pow(10, sigFigures - placeValues);
158+
var roundedNum = Math.Round(number * roundingFactor) / roundingFactor;
159+
160+
// Pad from right with zeroes to sigFigures length, so for 3 sig figs, 1.6 becomes 1.60
161+
var formattedNum = roundedNum.ToString("F" + sigFigures);
162+
var desiredLength = formattedNum.Contains('.') ? sigFigures + 1 : sigFigures;
163+
if (formattedNum.Length > desiredLength)
156164
{
157-
return number + $"10^{numDiv*3}";
165+
formattedNum = formattedNum.Substring(0, desiredLength);
158166
}
159167

160-
return number + _magnitudeAbbreviations[numDiv];
168+
formattedNum = formattedNum.TrimEnd('.');
169+
170+
if (numDiv >= _magnitudeAbbreviations.Length)
171+
{
172+
return formattedNum + $"10^{numDiv*3}";
173+
}
174+
175+
return formattedNum + _magnitudeAbbreviations[numDiv];
161176
}
162177
}
163178
}

0 commit comments

Comments
 (0)