How to convert an integer into its written‑out English words in C#

1 Answer

0 votes
using System;
using System.Text;

class NumberToWordsProgram
{
    private static readonly string[] Below20 = {
        "", "one", "two", "three", "four", "five", "six", "seven",
        "eight", "nine", "ten", "eleven", "twelve", "thirteen",
        "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
        "nineteen"
    };

    private static readonly string[] Tens = {
        "", "", "twenty", "thirty", "forty", "fifty",
        "sixty", "seventy", "eighty", "ninety"
    };

    private static string SetBelow20AndTens(int num) {
        if (num == 0)
            return "";

        if (num < 20)
            return Below20[num] + " ";

        if (num < 100)
            return Tens[num / 10] + " " + SetBelow20AndTens(num % 10);

        return Below20[num / 100] + " hundred " + SetBelow20AndTens(num % 100);
    }

    private static string NumberToWords(int num) {
        if (num == 0)
            return "zero";

        StringBuilder result = new StringBuilder();

        if (num >= 1_000_000_000) {
            result.Append(SetBelow20AndTens(num / 1_000_000_000)).Append("billion ");
            num %= 1_000_000_000;
        }

        if (num >= 1_000_000) {
            result.Append(SetBelow20AndTens(num / 1_000_000)).Append("million ");
            num %= 1_000_000;
        }

        if (num >= 1000) {
            result.Append(SetBelow20AndTens(num / 1000)).Append("thousand ");
            num %= 1000;
        }

        if (num > 0) {
            result.Append(SetBelow20AndTens(num));
        }

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

    static void Main()
    {
        int n = 176283;
        
        Console.WriteLine(NumberToWords(n));
    }
}


/*
run:

one hundred seventy six thousand two hundred eighty three

*/

 



answered 5 days ago by avibootz
...