lightbulb32
lightbulb32

Reputation: 13

C# convert int to English word

I would like to convert an integer into a word in the form of:

etc.

I have tried googling and have found answers on how to convert ints to plain english words like one, two, three etc. Does anyone know if there are any methods out there that do this already? I'd like to avoid writing my own if possible but I think that's what it will come to.

Upvotes: 0

Views: 885

Answers (2)

Ilian
Ilian

Reputation: 5355

If you're open to using a third-party library, you can use Humanizer. Sample usage from the link:

0.ToOrdinalWords() => "zeroth"
1.ToOrdinalWords() => "first"
2.ToOrdinalWords() => "second"
8.ToOrdinalWords() => "eighth"
10.ToOrdinalWords() => "tenth"
11.ToOrdinalWords() => "eleventh"
12.ToOrdinalWords() => "twelfth"
20.ToOrdinalWords() => "twentieth"
21.ToOrdinalWords() => "twenty first"
121.ToOrdinalWords() => "hundred and twenty first"

Upvotes: 0

BradleyDotNET
BradleyDotNET

Reputation: 61339

No, a mapping like that does not currently exist in C# (apart from any third party libraries of course).

Easy enough to do though:

Dictionary<int, string> specialNumberNames = new Dictionary<int, string>()
{
   {1, "First"},
   {2, "Second"},
   ...
}

int number = 1;
string specialName = specialNumberNames[number];

Upvotes: 3

Related Questions