Convert numbers to words in C#
In this article we will see how to convert integer numbers to its verbal representation, for example 25 = "twenty five". First we create this Window Form:
Then we add this function which convert numbers to words:
And in ConvertButton click event we add this code:
To understand more, check this video:
Then we add this function which convert numbers to words:
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;
}
And in ConvertButton click event we add this code:
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = NumberToWords(Convert.ToInt32(textBox1.Text));
}
To understand more, check this video:
References:
http://stackoverflow.com/questions/2729752/converting-numbers-in-to-words-c-sharp
Convert numbers to words in C#
Reviewed by Bloggeur DZ
on
10:46
Rating:
Aucun commentaire: