I'll show you a simple solution to convert an integer to words. It's useful when dealing with money or printing a receipt or check.
public static string ValueToWords(int number)
{
if (number == 0)
return "zero";
if (number < 0)
return "minus " + ValueToWords(Math.Abs(number));
string words = "";
if ((number / 1000000) > 0)
{
words += ValueToWords(number / 1000000) + " Million ";
number %= 1000000;
}
if ((number / 1000) > 0)
{
words += ValueToWords(number / 1000) + " Thousand ";
number %= 1000;
}
if ((number / 100) > 0)
{
words += ValueToWords(number / 100) + " Hundred ";
number %= 100;
}
if (number > 0)
{
if (words != "")
words += "and ";
var ones = new[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
var tens = new[] { "Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
if (number < 20)
words += ones[number];
else
{
words += tens[number / 10];
if ((number % 10) > 0)
words += " " + ones[number % 10];
}
}
return words;
}
Nice Code... based on this code i created an extension:
ReplyDeleteSo instead of passing the int/decimal value to a regular function
int i =150;
string words = ValueToWords(i);
Console.WriteLine(words);
we can just call the extended function
Console.WriteLine(i.ToWords());
See console code below for int. hope you could create a decimal version.
class Program
{
static void Main(string[] args)
{
int intValue;
Console.WriteLine("Please enter a integer value");
Int32.TryParse(Console.ReadLine(),out intValue);
Console.WriteLine(intValue.ToWords());
Console.ReadLine();
}
}
public static class Extensions
{
///
/// Converts a integer value to words
///
/// param name="number">the value to convert to word, the value must be from a int type property /param>
///
public static string ToWords(this int number)
{
if (number == 0)
return "zero";
if (number < 0)
return "minus " + ToWords(Math.Abs(number));
string words = "";
if ((number / 1000000) > 0)
{
words += ToWords(number / 1000000) + " Million ";
number %= 1000000;
}
if ((number / 1000) > 0)
{
words += ToWords(number / 1000) + " Thousand ";
number %= 1000;
}
if ((number / 100) > 0)
{
words += ToWords(number / 100) + " Hundred ";
number %= 100;
}
if (number > 0)
{
if (words != "")
words += "and ";
var ones = new[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
var tens = new[] { "Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
if (number < 20)
words += ones[number];
else
{
words += tens[number / 10];
if ((number % 10) > 0)
words += " " + ones[number % 10];
}
}
return words;
}
}