Skip to content

Commit ac3e013

Browse files
fix: refactor show large numbers
1 parent 085bd48 commit ac3e013

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

Extensions/NumberExtensions.cs

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,23 @@ public static class NumberExtensions
44
{
55
public static string StringifyLargeNumbers(this int value)
66
{
7-
if (value < 1000) return value.ToString();
7+
if (value < 1_000) return value.ToString();
88

9-
var valueStr = value.ToString();
10-
if (valueStr.Length is >= 4 and <= 6) return $"{valueStr[0]}.{valueStr[1]}K";
11-
if (valueStr.Length is >= 7 and <= 9) return $"{valueStr[0]}.{valueStr[1]}M";
12-
if (valueStr.Length is >= 10 and <= 12) return $"{valueStr[0]}.{valueStr[1]}B";
9+
if (value < 1_000_000)
10+
return FormatWithSuffix(value / 1_000, "K"); // Thousands: 1000-999999
1311

14-
throw new ArgumentException($"Number {value} is too large to stringify");
12+
if (value < 1_000_000_000)
13+
return FormatWithSuffix(value / 1_000_000, "M"); // Millions: 1000000-999999999
14+
15+
return FormatWithSuffix(value / 1_000_000_000, "B"); // Billions: 1000000000+
16+
}
17+
18+
private static string FormatWithSuffix(double value, string suffix)
19+
{
20+
if (value % 1 == 0)
21+
return $"{(int)value}{suffix}";
22+
23+
var formatted = $"{value:F1}{suffix}";
24+
return formatted.EndsWith(".0" + suffix) ? $"{(int)value}{suffix}" : formatted;
1525
}
1626
}

0 commit comments

Comments
 (0)