Wednesday, May 13, 2015

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. }

No comments:

Post a Comment