views:

258

answers:

4

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

How can I do this in C#?

+2  A: 

divide the number by 1000000.0, then append an "m".

remember to round the number to 1 decimal place.

John Boker
this works if it's always trying to do millions, but not if he wants thousands, millions, billions, etc.
Reed Copsey
the question asked about numbers like 4,316,000 as "4.3m", other formats were not in the requirements :)
John Boker
+8  A: 

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
Reed Copsey
Voted for truth.
Florian Doyon
+1  A: 
long valueToFormat = 4316000;
var dict = new Dictionary<long, string>() {
    {1000000000, "b"},
    {1000000, "m"},
    {1000, "k"}
 };

 string formattedValue = valueToFormat.ToString();
 foreach (long n in dict.Keys.OrderBy(k => k)) {
     if (valueToFormat < n) {
         continue;
     }
     double value = Math.Round(valueToFormat / (double)n, 1);
     formattedValue = String.Format("{0}{1}", value, dict[n]);
 }
 Console.WriteLine(formattedValue);
Jason
+1  A: 

If you're only running on Windows you could use a p-invoke declaration in C# or VB.NET to call the Win32 functions StrFormatByteSizeW or StrFormatByteSize64. If your application/site is guaranteed to be running on at least Vista SP1 or Server 2008 there's also StrFormatByteSizeEx with a few more options.

Sample from the MSDN docs:

Numeric value   Text string 
532             532 bytes 
1340            1.30KB 
23506           22.9KB 
2400016         2.29MB 
2400000000      2.23GB

These APIs also handle localization correctly for non-English users.

devstuff
This wouldn't do 4,316,000 as "4.3m", like the question asked, but rather "4.12MB"
Reed Copsey
Oops, read the question as regarding binary divisors, instead of decimal divisors.
devstuff