Number Words
This page was last reviewed on Sep 12, 2023.
Dot Net Perls
Number words. Consider that all numbers have English word representations. We convert the number "1" to the word "one" using the C# language.
static Array
Problem notes. Numbers can be represented as digits. But displaying English words for small numbers is desirable. This can help user interfaces.
int, uint
Input and output. This class handles small numbers specifically—large numbers like "six thousand thirty seven" are not supported.
INPUT: 1 OUTPUT: "one"
Example code. 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().
Main args
Info The NumberString.GetString method converts the integers to words if appropriate.
Warning This 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
Method notes. 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.
And If the test evaluates to true, the English word "zero", "one", "two" are returned.
A discussion. 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.
Info It is easier to tell the letter "l" from the word "one" and not the number "1".
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2024 Sam Allen.