Abbreviate numbers (Shorten numbers)

Date: 2021-09-27

Source: https://stackoverflow.com/a/40724354

For formatting / displaying large numbers (e.g. likes, views)

const SI_SYMBOL = ["", "k", "M", "G", "T", "P", "E"];

function abbreviateNumber(number){
    // what tier? (determines SI symbol)
    const tier = Math.log10(Math.abs(number)) / 3 | 0;

    // if zero, we don't need a suffix
    if(tier == 0) return number;

    // get suffix and determine scale
    const suffix = SI_SYMBOL[tier];
    const scale = 10 ** (tier * 3);

    // scale the number
    const scaled = number / scale;

    // format number and add suffix
    return scaled.toFixed(1) + suffix;
}

Source: https://stackoverflow.com/a/60988355

ES2020 adds support for this in Intl.NumberFormat Using notation as follows:

let formatter = Intl.NumberFormat('en', { notation: 'compact' });
// example 1
let million = formatter.format(1e6);
// example 2
let billion = formatter.format(1e9);
// print
console.log(million == '1M', billion == '1B');

C#

    private static readonly string[] SI_SYMBOL = { "", "k", "M", "G", "T", "P", "E" };


    public static string AbbreviateNumber(double number)
    {
        // Controleer op ongeldige getallen
        if (double.IsNaN(number)) return "NaN";
        if (double.IsInfinity(number)) return number > 0 ? "∞" : "-∞";

        // Controleer of het getal nul is
        if (number == 0) return "0";

        // Wat is de tier? (bepaalt SI-symbool)
        int tier = (int)(Math.Log10(Math.Abs(number)) / 3);

        // Als tier 0 is, geen suffix nodig
        if (tier == 0) return number.ToString();

        // Beperk tier tot beschikbare SI-symbolen
        tier = Math.Min(tier, SI_SYMBOL.Length - 1);

        // Haal het suffix op en bepaal de schaal
        string suffix = SI_SYMBOL[tier];
        double scale = Math.Pow(10, tier * 3);

        // Schaal het getal
        double scaled = number / scale;

        // Formatteer het getal en voeg suffix toe
        return $"{scaled:F1}{suffix}";
    }
53800cookie-checkAbbreviate numbers (Shorten numbers)