Can anyone teach me how to convert numbers to words? For example:
18,000.00
In words:
eighteen thousand
Hope anyone can help. I am using Visual Studio 2008 professional edition.
Can anyone teach me how to convert numbers to words? For example:
18,000.00
In words:
eighteen thousand
Hope anyone can help. I am using Visual Studio 2008 professional edition.
High level algorithm:
Break the number into three-digit groups
For each group {
if value > 0 {
Compute string translation
output string + group identifier (eg. million, thousand, etc)
}
}
The three-digit translation step would need to examine the hundreds digit and out it's string equivalent + " hundred and " if it's greater than 0. The remaining two digits could be used to index into a string array if < 20, or handled separately to index string arrays for each digit.
Here is the logic developed by Justin Rogers:
using System;
public class NumberToEnglish {
private static string[] onesMapping =
new string[] {
"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
"Sixteen", "Seventeen", "Eighteen", "Nineteen"
};
private static string[] tensMapping =
new string[] {
"Twenty", "Thirty", "Forty", "Fifty", "Sixty",
"Seventy", "Eighty", "Ninety"
};
private static string[] groupMapping =
new string[] {
"Hundred", "Thousand", "Million", "Billion", "Trillion"
};
private static void Main(string[] args) {
Console.WriteLine(EnglishFromNumber(long.Parse(args[0])));
}
private static string EnglishFromNumber(int number) {
return EnglishFromNumber((long) number);
}
private static string EnglishFromNumber(long number) {
if ( number == 0 ) {
return onesMapping[number];
}
string sign = "Positive";
if ( number < 0 ) {
sign = "Negative";
number = Math.Abs(number);
}
string retVal = null;
int group = 0;
while(number > 0) {
int numberToProcess = (int) (number % 1000);
number = number / 1000;
string groupDescription = ProcessGroup(numberToProcess);
if ( groupDescription != null ) {
if ( group > 0 ) {
retVal = groupMapping[group] + " " + retVal;
}
retVal = groupDescription + " " + retVal;
}
group++;
}
return sign + " " + retVal;
}
private static string ProcessGroup(int number) {
int tens = number % 100;
int hundreds = number / 100;
string retVal = null;
if ( hundreds > 0 ) {
retVal = onesMapping[hundreds] + " " + groupMapping[0];
}
if ( tens > 0 ) {
if ( tens < 20 ) {
retVal += ((retVal != null) ? " " : "") + onesMapping[tens];
} else {
int ones = tens % 10;
tens = (tens / 10) - 2; // 20's offset
retVal += ((retVal != null) ? " " : "") + tensMapping[tens];
if ( ones > 0 ) {
retVal += ((retVal != null) ? " " : "") + onesMapping[ones];
}
}
}
return retVal;
}
}