Home >Backend Development >C++ >How to Convert Numbers to Words in C#?

How to Convert Numbers to Words in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-24 14:17:10878browse

How to Convert Numbers to Words in C#?

C#digital transfer text detailed explanation

Converting numbers into text is a common task in programming. C# provides a direct method to implement this function. The following code example can be used as your starting point:

code points:
<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>

The function receives an integer as the input and returns a string of the form representation form.
  • The function processs negative numbers, and "minus" is added in front of the positive text after the conversion. NumberToWords
  • The function is grouped by the number of millions, thousands, and hundreds of them. For each group, it iterates the number and converts them into text, and uses
  • and
  • arrays.
  • unitsMap Functions add appropriate connector ("million", "thousand", "hundred" and "and") to form a final string. tensMap
  • This code can be used as a starting point for processing more complicated scenes, such as the number exceeding the range (-1000, 1000) or the number containing comma.

The above is the detailed content of How to Convert Numbers to Words in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn