Code/Extensions/LongExtensions.cs

Extension method for long that formats a number using SI-style 1000-based prefixes (k, M, G, T, P). It computes a 10^3 exponent, scales the value, and returns a string with up to two decimal places and the appropriate suffix.

🐞 Math.Abs(long.MinValue) overflows to a negative value so Math.Log10 returns NaN, exponent becomes 0, and the method formats long.MinValue without a prefix instead of throwing for out-of-range.
#nullable enable annotations

namespace LichessNET.Extensions;

public static class LongExtensions
{
    private static readonly string[] Prefixes = { "", "k", "M", "G", "T", "P" };

    public static string ToSIPrefix(this long number)
    {
        if (number == 0) return "0";

        int exponent = (int)Math.Floor(Math.Log10(Math.Abs(number)) / 3);
        double scaledNumber = number / Math.Pow(1000, exponent);

        if (exponent < 0 || exponent >= Prefixes.Length)
        {
            throw new ArgumentOutOfRangeException(nameof(number),
                "Number is too large or too small to format with SI prefixes.");
        }

        return $"{scaledNumber:0.##} {Prefixes[exponent]}";
    }
}