Search code examples
c#.netformattingnumbershumanize

Formatting Large Numbers with .NET


I have a requirement to format large numbers like 4,316,000 as "4.3m".

How can I do this in C#?


Solution

  • You can use Log10 to determine the correct break. Something like this could work:

    double number = 4316000;
    
    int mag = (int)(Math.Floor(Math.Log10(number))/3); // Truncates to 6, divides to 2
    double divisor = Math.Pow(10, mag*3);
    
    double shortNumber = number / divisor;
    
    string suffix;
    switch(mag)
    {
        case 0:
            suffix = string.Empty;
            break;
        case 1:
            suffix = "k";
            break;
        case 2:
            suffix = "m";
            break;
        case 3:
            suffix = "b";
            break;
    }
    string result = shortNumber.ToString("N1") + suffix; // 4.3m