Wednesday, May 13, 2015

Sample C# code to Generate linear Y axis value for a chart from the given amount.

Below is a sample C# code to Generate linear Y axis value for a chart from the given amount. You wil get the lower bound of the y axis value when you call the CalculateLowerBound method. That will be added itself based on the barCount in a loop to get the linear y axis values.
public List GenerateAxis()
{
 int barCount = 5;
 double amount = 10000;
 double money = CalculateLowerBound(amount, barCount);

 var axisVal = new List();

 double valX = 0;
 for (int i = 1; i <= barCount; i++)
 {
  valX += money;
  axisVal.Add(valX);
 }

 return axisVal;
}

public double CalculateLowerBound(double range, int barCount)
{
 double unroundedTickSize = range / (barCount);
 double x = Math.Ceiling(Math.Log10(unroundedTickSize) - 1);
 double pow10x = Math.Pow(10, x);
 return Math.Ceiling(unroundedTickSize / pow10x) * pow10x;
}

Sample C# code to shorten amount from 1 Trillion to 1T, 1 Billion to 1 B, 1 Million to 1M and 1 Thousand to 1K.

The following code can be used to shorten a amount from 1 Trillion to 1T, 1 Billion to 1 B, 1 Million to 1M and 1 Thousand to 1K. You can customize it to accept more number of scales amount like Quadrillion, Quintillion, Sextillion, Septillion etc.
public static string GetFormattedAmountText(double amount)
{
 var formattedAmount = string.Empty;

 var x = amount;  //the number to be evaluated
 var e = 0;    //to accumulate the scale
 var i = x;    //a working variable

 while (i > 1)
 {
  i = i / 10;
  e++;
 }

 if (e >= 12)
 {
  formattedAmount = x / 1E9 + "T";
 }
 else if (e >= 9)
 {
  formattedAmount = x / 1E9 + "B";
 }
 else if (e >= 6)
 {
  formattedAmount = x / 1E6 + "M";
 }
 else if (e >= 3)
 {
  formattedAmount = x / 1E3 + "K";
 }

 return formattedAmount;
}