Formatting large numbers in C#
Slight refactoring:
public static string KMBMaker( double num )
{
double numStr;
string suffix;
if( num < 1000d )
{
numStr = num;
suffix = "";
}
else if( num < 1000000d )
{
numStr = num/1000d;
suffix = "K";
}
else if( num < 1000000000d )
{
numStr = num/1000000d;
suffix = "M";
}
else
{
numStr = num/1000000000d;
suffix = "B";
}
return numStr.ToString() + suffix;
}
Use:
GoldDisplay.text = KMBMaker(gold);
Changes:
- Explicitly use
double
constants - Remove duplication
- Separate concerns - there's no need for this method to know about text boxes
i don't think there is a build-in method for that so i just maybe reinvented the wheel by writing my own way but this should be how i would maybe do it
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
for (double i = 500d; i < 5e23; i *= 100d)
{
Console.WriteLine(i.ToMyNumber());
}
Console.Read();
}
}
public static class helper
{
private static readonly List<string> myNum;
static helper()
{
myNum = new List<string>();
myNum.Add("");
myNum.Add("kilo");
myNum.Add("mill");
myNum.Add("bill");
myNum.Add("tril");
myNum.Add("quad");
myNum.Add("quin");
myNum.Add("sext");
// ....
}
public static string ToMyNumber(this double value)
{
string initValue = value.ToString();
int num = 0;
while (value >= 1000d)
{
num++;
value /= 1000d;
}
return string.Format("{0} {1} ({2})", value, myNum[num], initValue);
}
}
}
which print this
500 (500)
50 kilo (50000)
5 mill (5000000)
500 mill (500000000)
50 bill (50000000000)
5 tril (5000000000000)
500 tril (500000000000000)
50 quad (5E+16)
5 quin (5E+18)
500 quin (5E+20)
50 sext (5E+22)