Convert to a textual representation of a number

Using C # I need to convert an integer to this word representation and only go to 5 to 10. Is there a better way to do this than this?

static string[] numberwords = { "zero", "one", "two", "three", "four", "five" }; public static string GetNumberAsString(int value) { return numberwords[value]; } 
+4
source share
5 answers

How far do you have to go?

I assume that you will need several arrays to do what you need for the general case, for example, "one" after "twenty", "twenty" through "ninety" by tens, "thousands", "million", etc.

+1
source

Why don't you use an associative array ( Dictionary<int,string> in C #)? If you use this, you wonโ€™t have to worry about line order. Because it will become a nightmare as you add more numbers, and if they are not necessarily continuous. Of course, if your number range is very small, your approach will save you some space.

+1
source

For this specific case (a limited range of numbers), an interesting alternative would be to use an enumeration, and then transfer the conversion to a string in the extension method.

The code below shows the conversion from an enumeration value to a string using the extension method and an attempt to convert the value outside the enumeration range.

 public enum NumberWords { zero, one, two, three, four, five } public static class IntExtensions { public static string ToWord(this int input) { return ((NumberWords)input).ToString(); } } class Program { static void Main(string[] args) { Console.WriteLine(((NumberWords)5).ToString()); Console.WriteLine(0.ToWord()); Console.WriteLine(1.ToWord()); Console.WriteLine(2.ToWord()); Console.WriteLine(123.ToWord()); Console.ReadLine(); } } 
+1
source

Short :

No.

Long :

There is no way to do this in the .NET Framework. One suggestion for improvement: you can read the numbers from a language-specific configuration file.

0
source

To emulate the @Ravi sentence, you can search for each digit by place (one, tens, hundreds, etc.) in a user dictionary such as Dictionary<DigitPlace, Dictionary<int, string> (where you create and Enum for DigitPlace ) . Of course, that would be language specific.

Example:

 Ones, 1, "one" Ones, 2, "two" ... Tens, 3, "thirty-" ... Hundreds, 6, "six-hundred" ... 

If you want to follow my suggestion to create a type expander, here is an example.

 public enum NumberedWords { zero = 0, one = 1, two = 2, three = 3, four = 4, five = 5 } public static string ToName(this int value) { return (NumberedWords)value; } 

Using:

 int number = 5; string numberName = number.ToName(); 
0
source

All Articles