C#数字转文字详解
将数字转换为文字是编程中常见的任务,C# 提供了一种直接的方法来实现此功能。以下代码示例可以作为您的起点:
<code class="language-csharp">public static string NumberToWords(int number) { string words = ""; if (number < 0) { words += "minus "; number = -number; } if (number == 0) return "zero"; if (number >= 1000000) { words += NumberToWords(number / 1000000) + " million "; number %= 1000000; } if (number >= 1000) { words += NumberToWords(number / 1000) + " thousand "; number %= 1000; } if (number >= 100) { words += NumberToWords(number / 100) + " hundred "; number %= 100; } if (number > 0) { if (words != "") words += "and "; string[] unitsMap = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; string[] tensMap = { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; if (number < 20) words += unitsMap[number]; else { words += tensMap[number / 10]; if (number % 10 > 0) words += "-" + unitsMap[number % 10]; } } return words.Trim(); }</code>
代码要点:
NumberToWords
函数接收一个整数作为输入,并返回其文字表示形式的字符串。unitsMap
和 tensMap
数组。此代码可作为处理更复杂场景的起点,例如处理超出范围 (-1000, 1000) 的数字或包含逗号的数字。
以上是如何将数字转换为C#中的单词?的详细内容。更多信息请关注PHP中文网其他相关文章!