Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET or 3rd party library to convert number into "first", "second", "third", etc..."

Tags:

c#

.net

As in the title, does anyone know if there's a place in .NET, or a 3rd party library, where integers can be converted to their "ordering" counterparts.

1 - first
2 - second
3 - third
etc...

I could of course just write one myself, but I'd rather reuse something already existing if possible.

Thanks.

like image 327
MgSam Avatar asked Sep 18 '12 14:09

MgSam


2 Answers

Humanizer is a great library for this: Humanizr

Install-Package Humanizer

With Humanizer, you'd do:

int number = 5;
string ordinal = number.ToOrdinalWords()
like image 168
Chris Hynes Avatar answered Oct 15 '22 03:10

Chris Hynes


converting numbers in to words C#

Similiar to this question. You can get what you need from LukeH's answer:

public static string NumberToWords(int number)
{
if (number == 0)
    return "zero";

if (number < 0)
    return "minus " + NumberToWords(Math.Abs(number));

string words = "";

if ((number / 1000000) > 0)
{
    words += NumberToWords(number / 1000000) + " million ";
    number %= 1000000;
}

if ((number / 1000) > 0)
{
    words += NumberToWords(number / 1000) + " thousand ";
    number %= 1000;
}

if ((number / 100) > 0)
{
    words += NumberToWords(number / 100) + " hundred ";
    number %= 100;
}

if (number > 0)
{
    if (words != "")
        words += "and ";

    var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
    var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

    if (number < 20)
        words += unitsMap[number];
    else
    {
        words += tensMap[number / 10];
        if ((number % 10) > 0)
            words += "-" + unitsMap[number % 10];
    }
}

return words;
}
like image 41
Darren Avatar answered Oct 15 '22 04:10

Darren