要舍入文本的数字

时间:2018-02-13 09:29:52

标签: c#

我使用以下函数将数字转换为文本:

public static string NumberToText(long number)
{
   StringBuilder wordNumber = new StringBuilder();

   string[] powers = new string[] { "Thousand ", "Million ", "Billion " };
   string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
   string[] ones = new string[] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", 
                               "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };

   if (number == 0) { return "Zero"; }
   if (number < 0)
   {
       wordNumber.Append("Negative ");
       number = -number;
   }

   long[] groupedNumber = new long[] { 0, 0, 0, 0 };
   int groupIndex = 0;

   while (number > 0)
   {
       groupedNumber[groupIndex++] = number % 1000;
       number /= 1000;
   }

   for (int i = 3; i >= 0; i--)
   {
       long group = groupedNumber[i];

       if (group >= 100)
       {
           wordNumber.Append(ones[group / 100 - 1] + " Hundred ");
           group %= 100;

           if (group == 0 && i > 0)
               wordNumber.Append(powers[i - 1]);
       }

       if (group >= 20)
       {
           if ((group % 10) != 0)
               wordNumber.Append(tens[group / 10 - 2] + " " + ones[group % 10 - 1] + " ");
           else
               wordNumber.Append(tens[group / 10 - 2] + " ");
       }
       else if (group > 0)
           wordNumber.Append(ones[group - 1] + " ");

       if (group != 0 && i > 0)
           wordNumber.Append(powers[i - 1]);
   }

   return wordNumber.ToString().Trim();
}

这很好用。

问题是返回的文本太长而无法阅读。我想把它转换成更短的东西。

例如: 345435234 以三亿四千五百万,四十五万五千二百三十四返回。

我反而想要345.4 Mil。

以下是一些例子:

3454 should be 3.4K  
34543 should be 34.5K  
345433 should be 345.4K  
... and so on.

我如何实现这一目标?

2 个答案:

答案 0 :(得分:4)

也许是这样的?

虽然如果你有“可打印角色OCD ”,你可能会把它缩小

private static string[] suffixes = new[] { "", "K", "Mill", "Bill", "Trill", "Zill" };

public static string ToStuff(double number, int precision = 2)
{
    const double unit = 1000;
    var  i = 0;
    while (number > unit)
    {
        number /= unit;
        i++;
    }
    if(i >= 5) throw new Exception("No one can count this high");
    return Math.Round(number, precision, MidpointRounding.AwayFromZero) + suffixes[i];
}

免责声明 :完全未经测试

更新

由于受欢迎的需求,我使用1 E.g 2500000, 0的测试用例对其进行了测试,并输出2Mill。我想我可能在这个计数游戏中有职业生涯

更新2

由于更受欢迎的需求,我们的共识是我们不应该使用.Net默认舍入ToEven(银行家四舍五入),并且应该使用AwayFromZero

答案 1 :(得分:1)

尝试以下方法:

if (number>1000000)
   string = floor(number/1000000).ToString() + "m";
else if (number > 1000)
   string = floor(number/1000).ToString() + "k";
else
   string = number.ToString();