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.
  1. public List GenerateAxis()
  2. {
  3. int barCount = 5;
  4. double amount = 10000;
  5. double money = CalculateLowerBound(amount, barCount);
  6. var axisVal = new List();
  7. double valX = 0;
  8. for (int i = 1; i <= barCount; i++)
  9. {
  10. valX += money;
  11. axisVal.Add(valX);
  12. }
  13. return axisVal;
  14. }
  15. public double CalculateLowerBound(double range, int barCount)
  16. {
  17. double unroundedTickSize = range / (barCount);
  18. double x = Math.Ceiling(Math.Log10(unroundedTickSize) - 1);
  19. double pow10x = Math.Pow(10, x);
  20. return Math.Ceiling(unroundedTickSize / pow10x) * pow10x;
  21. }

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.
  1. public static string GetFormattedAmountText(double amount)
  2. {
  3. var formattedAmount = string.Empty;
  4.  
  5. var x = amount; //the number to be evaluated
  6. var e = 0; //to accumulate the scale
  7. var i = x; //a working variable
  8.  
  9. while (i > 1)
  10. {
  11. i = i / 10;
  12. e++;
  13. }
  14.  
  15. if (e >= 12)
  16. {
  17. formattedAmount = x / 1E9 + "T";
  18. }
  19. else if (e >= 9)
  20. {
  21. formattedAmount = x / 1E9 + "B";
  22. }
  23. else if (e >= 6)
  24. {
  25. formattedAmount = x / 1E6 + "M";
  26. }
  27. else if (e >= 3)
  28. {
  29. formattedAmount = x / 1E3 + "K";
  30. }
  31.  
  32. return formattedAmount;
  33. }