Consider that all numbers have English word representations. We convert the number "1" to the word "one" using the C# language.
Numbers can be represented as digits. But displaying English words for small numbers is desirable. This can help user interfaces.
This class
handles small numbers specifically—large numbers like "six thousand thirty seven" are not supported.
INPUT: 1 OUTPUT: "one"
The NumberString
class
contains the static
data and static
method used to convert integers to English words. We invoke a method from NumberString
in Main()
.
NumberString.GetString
method converts the integers to words if appropriate.class
does not support every case, and it (most importantly) only supports small integers.using System; static class NumberString { static string[] _words = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" }; public static string GetString(int value) { // See if the number can easily be represented by an English word. // ... Otherwise, return the ToString result. if (value >= 0 && value <= 10) { return _words[value]; } return value.ToString(); } } class Program { static void Main() { // Call the GetString method to get number words. Console.WriteLine(NumberString.GetString(0)); Console.WriteLine(NumberString.GetString(5)); Console.WriteLine(NumberString.GetString(10)); Console.WriteLine(NumberString.GetString(100)); } }zero five ten 100
The NumberString
class
is a static
class
. The GetString
method receives one formal parameter, an int
. It sees if this int
is between 0 and 10 inclusive.
In writing, editing guidelines will require that you type out numbers such as 0 to 10 as the words "zero" to "ten". The main benefit here is clarity.
We implemented text substitutions for small integers. We used a static
array and a lookup method. The program handles certain parameters with the lookup table.