c# - 将整数转换为书面数字

标签 c# integer

是否有一种有效的方法将整数转换为书面数字,例如:

string Written = IntegerToWritten(21);

将返回“二十一”。

有没有不涉及大量查找表的方法来做到这一点?

最佳答案

这应该工作得相当好:

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

    private static string FriendlyInteger(int n, string leftDigits, int thousands)
    {
        if (n == 0)
        {
            return leftDigits;
        }

        string friendlyInt = leftDigits;

        if (friendlyInt.Length > 0)
        {
            friendlyInt += " ";
        }

        if (n < 10)
        {
            friendlyInt += ones[n];
        }
        else if (n < 20)
        {
            friendlyInt += teens[n - 10];
        }
        else if (n < 100)
        {
            friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0);
        }
        else if (n < 1000)
        {
            friendlyInt += FriendlyInteger(n % 100, (ones[n / 100] + " Hundred"), 0);
        }
        else
        {
            friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, "", thousands+1), 0);
            if (n % 1000 == 0)
            {
                return friendlyInt;
            }
        }

        return friendlyInt + thousandsGroups[thousands];
    }

    public static string IntegerToWritten(int n)
    {
        if (n == 0)
        {
            return "Zero";
        }
        else if (n < 0)
        {
            return "Negative " + IntegerToWritten(-n);
        }

        return FriendlyInteger(n, "", 0);
    }
}

(编辑以修复带有百万、十亿等的错误)

关于c# - 将整数转换为书面数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3213/

相关文章:

c# - 如何使用 FirstOrDefault 避免 Object reference not set to instance of object 错误?

c - 数组索引和通常的算术转换

java - 如何将两个或多个数字分开并分别相加

java - 在实现检测输入是否为整数的系统时遇到困难

integer - 我们如何理解 Julia 中十六进制数与十进制数的加法?

c# - 为什么这行代码不起作用?

c# - 什么时候使用 CanFreeze?

c# - System.Printing 未找到(C#)?

c# - ASP.NET MVC3 和 MongoDB

python - 将指数表示法数字转换为字符串 - 解释