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中文網其他相關文章!