Related
Does anyone knows how to convert an integer to a long ordinal word in C# ?
Is easy to convert 1 to 1st, 2 to 2nd using this algorithm described here: Is there an easy way to create ordinals in C#?. But i need a way to convert 1 to the long ordinal word version. For example:
1 => First
2 => Second
3 => Third
...
9 => Ninth
and so on for any number.
The solution can not either create an infinite dictionary list with key par values of (1, "first", 2, "second", etc, etc)
I too cant find the exact solution for that.But I managed to get the answer.Try this,It will be useful.
public string ConvertNumbertoWordsFirst(long number)
{
string words = "";
words = ConvertNumbertoWords(number);
words = words.TrimEnd('\\');
if (words.EndsWith("One"))
{
words = words.Remove(words.LastIndexOf("One") + 0).Trim();
words = words + "First";
}
else if (words.EndsWith("Two"))
{
words = words.Remove(words.LastIndexOf("Two") + 0).Trim();
words = words + "Second";
}
else if (words.EndsWith("Three"))
{
words = words.Remove(words.LastIndexOf("Three") + 0).Trim();
words = words + "Third";
}
else if (words.EndsWith("Five"))
{
words = words.Remove(words.LastIndexOf("Five") + 0).Trim();
words = words + "Fifth";
}
else if (words.EndsWith("Eight"))
{
words = words.Remove(words.LastIndexOf("Eight") + 0).Trim();
words = words + "Eighth";
}
else if (words.EndsWith("Nine"))
{
words = words.Remove(words.LastIndexOf("Nine") + 0).Trim();
words = words + "Ninth";
}
else
{
words = words + "th";
}
return words;
}
ConvertNumbertoWords() is the function i got it from the below link.
Link : converting numbers in to words C#
public string ConvertNumbertoWords(long number)
{
if (number == 0) return "Zero";
if (number < 0) return "minus " + ConvertNumbertoWords(Math.Abs(number));
string words = "";
if ((number / 100000) > 0)
{
words += ConvertNumbertoWords(number / 100000) + " Lakhs ";
number %= 100000;
}
if ((number / 1000) > 0)
{
words += ConvertNumbertoWords(number / 1000) + " Thousand ";
number %= 1000;
}
if ((number / 100) > 0)
{
words += ConvertNumbertoWords(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;
}
I am trying to make a simple number to english words program and I've decided to use arrays. However whenever I enter a number greater than 99, I get an error in the third if clause.. What do I need to change to fix that? Here's my code;
class Program
{
static void Main(string[] args)
{
string[] uptonineteen = {"Zero","One","Two","Three","Four",
"Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen","Fourteen","Fifteen",
"Sixteen","Seventeen","Eighteen","Nineteen"};
string[] ten = {"","","Twenty","Thirty","Forty","Fifty",
"Sixty","Seventy","Eighty","Ninety",};
Console.WriteLine(" ---------------");
int i = int.Parse(Console.ReadLine());
if (i < 20)
{
Console.WriteLine(uptonineteen[i]);
}
if (i < 100)
{
Console.WriteLine(ten[i / 10] + ((i % 10 > 0) ? "" + uptonineteen[i%10] : ""));
}
if (i <= 999)
{
object lenthree = ten[i / 100] + "hundred"+" " + ((i % 100 > 0) ? "and" +" "+ uptonineteen[i % 1000] : "");
Console.WriteLine(lenthree);
}
Console.ReadKey();
}
}
}
Try this...
class Program
{
static void Main(string[] args)
{
string[] uptonineteen = {"Zero","One","Two","Three","Four",
"Five","Six","Seven","Eight","Nine","Ten",
"Eleven","Twelve","Thirteen","Fourteen","Fifteen",
"Sixteen","Seventeen","Eighteen","Nineteen"};
string[] ten = {"", "","Twenty","Thirty","Forty","Fifty",
"Sixty","Seventy","Eighty","Ninety",};
Console.WriteLine(" ---------------");
int i = int.Parse(Console.ReadLine());
if (i < 20)
{
Console.WriteLine(uptonineteen[i]);
}
else if (i < 100)
{
Console.WriteLine(((((i % 100) / 10) > 1) ? ten[((i % 100) / 10)] + ((i % 10) > 0 ? " " + uptonineteen[(i % 10)] : "") : " and " + uptonineteen[i % 100]));
}
else if (i <= 999)
{
object lenthree = uptonineteen[(i % 1000) / 100] + " hundred " + ((((i % 100) / 10) > 1) ? ten[((i % 100) / 10)] + ((i % 10) > 0 ? " " + uptonineteen[(i % 10)] : "") : " and " + uptonineteen[i % 100]);
Console.WriteLine(lenthree);
}
Console.ReadLine();
}
}
I've seen this too many times... This one handles, such as doing check writing and you may need to go into millions, thousands and includes cents at the end...
public class NumToWords
{
public NumToWords()
{}
string[] OneToNineteen =
{ "zero",
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
// empty string for zero-place-holder for tens grouping
string[] Tens = { "", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
// leave blank for "hundreds" because you would NOT do 123 as One hundred twenty-three hundred.
string[] Block3Section = { "", "thousand", "million", "billion" };
public string ToEnglish(int num)
{
int Block3Seq = 0;
int curSegment;
int tmp;
string FinalWords = "";
string curWord = "";
while (num > 0)
{
curSegment = num % 1000; // get only 3 digits worth (right) of the number
num = (num - curSegment) / 1000; // subtract this portion from the value
if (curSegment > 0)
{
// always add the closing word as we HAVE something to build out
curWord = "";
// how many "hundreds" of the current segment
tmp = (int)curSegment / 100;
if (tmp > 0)
curWord += " " + OneToNineteen[tmp] + " hundred";
// what is remainder of this 100 based segment
tmp = curSegment % 100;
if (tmp < 20)
curWord += " " + OneToNineteen[tmp];
else
{
curWord += " " + Tens[(int)tmp / 10]
+ '-' + OneToNineteen[tmp % 10];
}
// always add the closing word as we HAVE something to build out
curWord += " " + Block3Section[Block3Seq];
// add the section above to the overall words
FinalWords = curWord + FinalWords;
}
// to allow the next closing word for segment such as thousand, million, billion, etc
Block3Seq++;
}
return FinalWords;
}
}
string lenthree = ten[i / 100] + "hundred" + " " +
((i % 100 > 0) ? "and" + " " + uptonineteen[i % 100] : "");
The last 1000 should be 100. But since your uptonineteen isn't full, you still can't enter full numbers correctly.
After handling a case number > x you should continue with the remainder number = number % x or number %= x which is the same. Also you should really make the distinction between getting the English text and doing tests on the console. Console.WriteLines and Console.ReadKeys should not appear withing the logic. Build the English string using a StringBuilder by using this general structure:
public static string ToEnglish(int number)
{
var sb = new StringBuilder();
if (number >= 100) {
...
number %= 100;
}
if (sb.Length > 0 && number != 0) {
sb.Append("and ");
}
if (number >= 20) {
...
number %= 10;
}
if (sb.Length == 0 || number != 0) {
...
}
return sb.ToString();
}
Note: I don't post a complete solution since I assume its homework.
The console test looks like this
while (true) {
Console.Write("Please enter a number or `q` to quit: ");
string s = Console.ReadLine();
if (s == "q") {
break;
}
int i = int.Parse(s);
Console.WriteLine(ToEnglish(i));
}
string[] ones = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirtheen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen","nineteen", "twenty" };
string[] tens = { "Ten", "Twenty", "Thirthy", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
Console.WriteLine("Enter a number");
int i = int.Parse(Console.ReadLine());
if (i < 20)
{
Console.WriteLine(ones[i]);
}
if (i > 30 & i < 100)
{
Console.WriteLine(tens[((i%100)/10)-1]+ " " + ones[(i % 10)]);
}
if (i > 100 & i < 1000)
{
if (((i % 100) % 10) == 0)
{
Console.WriteLine(ones[(i / 100)] + " hundred " + tens[((i % 100) / 10) - 1]);
}
else
{
Console.WriteLine(ones[(i / 100)] + " hundred " + tens[((i % 100) / 10) - 1] + " and " + ones[((i % 100) % 10)]);
}
}
Console.ReadLine();
I have most of this done but am confused on how I would add the "twenties" I have all the "ones" and "teens" but it stops at 119 because I do not have the "twenties". In static string ThreeDigit is where I have it set up to do the three digit numbers.
{
class Program
{
static string[] digitWords =
{ "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
static string[] tenWords =
{ "", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety" };
static string[] hundredWords = { "", "One-hundred", "two-hundred", "three-hundred", "four-hundred", "five-hundred", "six-hundred", "seven-hundred", "eight-hundred", "nine-hundred"};
static string TwoDigit(int num)
{
if (num < 0 || num > 1001) return "";
if (num < 20) return digitWords[num];
if (num % 10 == 0)
return tenWords[num / 10];
else
return tenWords[num / 10] + "-" + digitWords[num % 10];
}
static string ThreeDigit(int num)
{
if (num % 100 == 0)
return hundredWords[num / 100];
else
return hundredWords[num / 100] + "-" + digitWords[num % 100];
}
static void Main(string[] args)
{
for (int i = 0; i <= 19; i++)
Console.WriteLine("{0}: {1}", i, TwoDigit(i));
for (int i = 20; i <= 99; i +=7)
Console.WriteLine("{0}: {1}", i, TwoDigit(i));
for (int i = 100; i <= 1100; i ++)
Console.WriteLine("{0}: {1}", i, ThreeDigit(i));
}
}
}
here is a good working solution: http://www.blackbeltcoder.com/Articles/strings/converting-numbers-to-words
try:
else
return hundredWords[num / 100] + " and " + TwoDigit(num);
}
I'm sure this has been done a hundred times, but i'm hoping there is a really simple way to accomplished this. I'm wanting to change words to an int.
Like the following example
One = 1
Two = 2
Three = 3
So basically if I have the string "One" it gets converted to 1, even if I could get back a string "1" I can just convert that.
Did this for fun... there's probably many edge cases that would fail...
private static Dictionary<string,long> numberTable=
new Dictionary<string,long>
{{"zero",0},{"one",1},{"two",2},{"three",3},{"four",4},
{"five",5},{"six",6},{"seven",7},{"eight",8},{"nine",9},
{"ten",10},{"eleven",11},{"twelve",12},{"thirteen",13},
{"fourteen",14},{"fifteen",15},{"sixteen",16},
{"seventeen",17},{"eighteen",18},{"nineteen",19},{"twenty",20},
{"thirty",30},{"forty",40},{"fifty",50},{"sixty",60},
{"seventy",70},{"eighty",80},{"ninety",90},{"hundred",100},
{"thousand",1000},{"million",1000000},{"billion",1000000000},
{"trillion",1000000000000},{"quadrillion",1000000000000000},
{"quintillion",1000000000000000000}};
public static long ToLong(string numberString)
{
var numbers = Regex.Matches(numberString, #"\w+").Cast<Match>()
.Select(m => m.Value.ToLowerInvariant())
.Where(v => numberTable.ContainsKey(v))
.Select(v => numberTable[v]);
long acc = 0,total = 0L;
foreach(var n in numbers)
{
if(n >= 1000)
{
total += (acc * n);
acc = 0;
}
else if(n >= 100){
acc *= n;
}
else acc += n;
}
return (total + acc) * ( numberString.StartsWith("minus",
StringComparison.InvariantCultureIgnoreCase) ? -1 : 1);
}
Here's a method that does that. If you need a wider range, it's easily extensible; just use a long, a ulong, or even a BigInt, and add more items to the modifiers dictionary.
static int ParseEnglish(string number) {
string[] words = number.ToLower().Split(new char[] {' ', '-', ','}, StringSplitOptions.RemoveEmptyEntries);
string[] ones = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
string[] teens = {"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
string[] tens = {"ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
Dictionary<string, int> modifiers = new Dictionary<string, int>() {
{"billion", 1000000000},
{"million", 1000000},
{"thousand", 1000},
{"hundred", 100}
};
if(number == "eleventy billion")
return int.MaxValue; // 110,000,000,000 is out of range for an int!
int result = 0;
int currentResult = 0;
int lastModifier = 1;
foreach(string word in words) {
if(modifiers.ContainsKey(word)) {
lastModifier *= modifiers[word];
} else {
int n;
if(lastModifier > 1) {
result += currentResult * lastModifier;
lastModifier = 1;
currentResult = 0;
}
if((n = Array.IndexOf(ones, word) + 1) > 0) {
currentResult += n;
} else if((n = Array.IndexOf(teens, word) + 1) > 0) {
currentResult += n + 10;
} else if((n = Array.IndexOf(tens, word) + 1) > 0) {
currentResult += n * 10;
} else if(word != "and") {
throw new ApplicationException("Unrecognized word: " + word);
}
}
}
return result + currentResult * lastModifier;
}
Here's a C# version of the algorithm above. I renamed and rewrote some code for clarity and added support for negative numbers, hyphenated numbers, zero, and combinations of text words and digits (like "100 and 5"). Thank you to Ry- for the great start.
/// <summary>
/// Convert text number strings to integer numbers. Credit to stackoverflow
/// for the main algorithm.
/// </summary>
public static int
WordNumberToInt (string number) {
// define arrays of keywords to translate text words to integer positions
// in the arrays. Thus, ordering of words in the array is important.
string[] ones = {
"one", "two", "three", "four", "five", "six",
"seven", "eight", "nine"
};
string[] teens = {
"eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
string[] tens = {
"ten", "twenty", "thirty", "forty", "fifty", "sixty",
"seventy", "eighty", "ninety"
};
var bigscales = new Dictionary<string, int> () {
{"hundred", 100}, {"hundreds", 100}, {"thousand", 1000},
{"million", 1000000}, {"billion", 1000000000},
};
string[] minusWords = {"minus", "negative"};
var splitchars = new char[] {' ', '-', ','};
// flip all words to lowercase for proper matching
var lowercase = number.ToLower ();
var inputwords = lowercase.Split (splitchars, StringSplitOptions.RemoveEmptyEntries);
// initalize loop variables and flags
int result = 0;
int currentResult = 0;
int bigMultiplierValue = 1;
bool bigMultiplierIsActive = false;
bool minusFlag = false;
foreach (string curword in inputwords) {
// input words are either bigMultipler words or little words
//
if (bigscales.ContainsKey (curword)) {
bigMultiplierValue *= bigscales[curword];
bigMultiplierIsActive = true;
}
else {
// multiply the current result by the previous word bigMultiplier
// and disable the big multiplier until next time
if (bigMultiplierIsActive) {
result += currentResult * bigMultiplierValue;
currentResult = 0;
bigMultiplierValue = 1; // reset the multiplier value
bigMultiplierIsActive = false; // turn it off until next time
}
// translate the incoming text word to an integer
int n;
if ((n = Array.IndexOf (ones, curword) + 1) > 0) {
currentResult += n;
}
else if ((n = Array.IndexOf (teens, curword) + 1) > 0) {
currentResult += n + 10;
}
else if ((n = Array.IndexOf (tens, curword) + 1) > 0) {
currentResult += n * 10;
}
// allow for negative words (like "minus")
else if (minusWords.Contains (curword)) {
minusFlag = true;
}
// allow for phrases like "zero 500" hours military time
else if (curword == "zero") {
continue;
}
// allow for text digits too, like "100 and 5"
else if (int.TryParse (curword, out int tmp)) {
currentResult += tmp;
}
else if (curword != "and") {
throw new ApplicationException ("Expected a number: " + curword);
}
}
}
var final = result + currentResult * bigMultiplierValue;
if (minusFlag)
final *= -1;
return final;
}
Here are some test cases that I ran.
-20 = minus twenty
-261 = minus two hundred sixty one
1965 = nineteen hundred and sixty five
45 = forty five
55 = fifty-five
21 = twenty-one
55 = fifty five
0 = zero
105 = one hundred 5
105 = 100 and 5
I took a slightly different approach to error handling…
public static bool ParseEnglishNumberPhrase(string pNumberPhrase, out int pValue) {
pValue = 0;
string[]
temporaryWords = pNumberPhrase.ToLower().Split(new char[] { '_', ' ', '-', ',' }, StringSplitOptions.RemoveEmptyEntries),
ones = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" },
teens = { "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" },
tens = { "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" },
minusWords = { "minus", "negative", "hyphen" };
List<string> words = temporaryWords.ToList();
bool minusFlag = false;
Dictionary<string, int> modifiers = new Dictionary<string, int>() {
{ "billion", 1000000000 },
{ "million", 1000000 },
{ "thousand", 1000 },
{ "hundred", 100 } };
int result = 0, currentResult = 0, lastModifier = 1;
if (pNumberPhrase.Equals("eleventy billion")) {
pValue = int.MaxValue; // 110,000,000,000 is out of range for an int!
return false;
}
if (words[0].Equals("zero") && (words.Count == 1)) {
pValue = 0;
return true;
}
else if (words[0].Equals("zero"))
words.RemoveAt(0);
if (pNumberPhrase.StartsWith("-"))
minusFlag = true;
foreach (string word in minusWords) {
if (pNumberPhrase.Contains(word)) {
minusFlag = true;
words.Remove(word);
}
}
if (words.Count == 1) {
if (int.TryParse(words[0], out int pOutValue)) {
pValue = pOutValue;
if (minusFlag)
pValue *= -1;
return true;
}
}
foreach (string word in words) {
if (modifiers.ContainsKey(word))
lastModifier *= modifiers[word];
else {
int n;
if (lastModifier > 1) {
result += currentResult * lastModifier;
lastModifier = 1;
currentResult = 0;
}
if ((n = Array.IndexOf(ones, word) + 1) > 0)
currentResult += n;
else if ((n = Array.IndexOf(teens, word) + 1) > 0)
currentResult += n + 10;
else if ((n = Array.IndexOf(tens, word) + 1) > 0)
currentResult += n * 10;
else if (word != "and") {
pValue = -1;
return false;
}
}
}
pValue = result + currentResult * lastModifier;
if (minusFlag)
pValue *= -1;
return true;
}
I think a far easier to understand solution is as follows:
public static int ParseInt(string s)
{
var wordArray = s.Split(' ', '-');
int finalNumber = 0;
Dictionary<string, int> additionWords = new Dictionary<string, int>{
{"one" , 1}, {"two", 2},{"three", 3},{"four", 4},{"five", 5},{"six", 6},
{"seven", 7},{"eight", 8},{"nine", 9},{"ten", 10},{"eleven", 11},{"twelve", 12},
{"thirteen", 13},{"fourteen", 14},{"fifteen", 15},{"sixteen", 16},{"seventeen", 17},
{"eighteen", 18},{"nineteen", 19},{"twenty", 20},{"thirty", 30},{"forty", 40},
{"fifty", 50},{"sixty", 60},{"seventy", 70},{"eighty", 80},{"ninety", 90}
};
Dictionary<string, int> multiplicationWords = new Dictionary<string, int>{
{"hundred", 100},{"thousand", 1000},{"million", 1000000}
};
int multiplier = 1;
for (int i = wordArray.Length - 1; i >= 0; i--){
if (additionWords.ContainsKey(wordArray[i])){
finalNumber += additionWords[wordArray[i]] * multiplier;
}
if (multiplicationWords.ContainsKey(wordArray[i])){
if (multiplicationWords[wordArray[i]] < multiplier){
multiplier *= multiplicationWords[wordArray[i]];
}else{
multiplier = multiplicationWords[wordArray[i]];
}
}
}
return finalNumber;
}
Is there an efficient method of converting an integer into the written numbers, for example:
string Written = IntegerToWritten(21);
would return "Twenty One".
Is there any way of doing this that doesn't involve a massive look-up table?
This should work reasonably well:
public static class HumanFriendlyInteger
{
static string[] ones = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
static string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
static string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
static string[] thousandsGroups = { "", " Thousand", " Million", " Billion" };
private static string FriendlyInteger(int n, string leftDigits, int thousands)
{
if (n == 0)
{
return leftDigits;
}
string friendlyInt = leftDigits;
if (friendlyInt.Length > 0)
{
friendlyInt += " ";
}
if (n < 10)
{
friendlyInt += ones[n];
}
else if (n < 20)
{
friendlyInt += teens[n - 10];
}
else if (n < 100)
{
friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0);
}
else if (n < 1000)
{
friendlyInt += FriendlyInteger(n % 100, (ones[n / 100] + " Hundred"), 0);
}
else
{
friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, "", thousands+1), 0);
if (n % 1000 == 0)
{
return friendlyInt;
}
}
return friendlyInt + thousandsGroups[thousands];
}
public static string IntegerToWritten(int n)
{
if (n == 0)
{
return "Zero";
}
else if (n < 0)
{
return "Negative " + IntegerToWritten(-n);
}
return FriendlyInteger(n, "", 0);
}
}
(Edited to fix a bug w/ million, billion, etc.)
I use this handy library called Humanizer.
https://github.com/Humanizr/Humanizer
It supports several cultures and converts not only numbers to words but also date and it's very simple to use.
Here's how I use it:
int someNumber = 543;
var culture = System.Globalization.CultureInfo("en-US");
var result = someNumber.ToWords(culture); // 543 -> five hundred forty-three
And voilá!
I use this code.It is VB code but you can easily translate it to C#. It works
Function NumberToText(ByVal n As Integer) As String
Select Case n
Case 0
Return ""
Case 1 To 19
Dim arr() As String = {"One","Two","Three","Four","Five","Six","Seven", _
"Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen", _
"Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"}
Return arr(n-1) & " "
Case 20 to 99
Dim arr() as String = {"Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"}
Return arr(n\10 -2) & " " & NumberToText(n Mod 10)
Case 100 to 199
Return "One Hundred " & NumberToText(n Mod 100)
Case 200 to 999
Return NumberToText(n\100) & "Hundreds " & NumberToText(n mod 100)
Case 1000 to 1999
Return "One Thousand " & NumberToText(n Mod 1000)
Case 2000 to 999999
Return NumberToText(n\1000) & "Thousands " & NumberToText(n Mod 1000)
Case 1000000 to 1999999
Return "One Million " & NumberToText(n Mod 1000000)
Case 1000000 to 999999999
Return NumberToText(n\1000000) & "Millions " & NumberToText(n Mod 1000000)
Case 1000000000 to 1999999999
Return "One Billion " & NumberTotext(n Mod 1000000000)
Case Else
Return NumberToText(n\1000000000) & "Billion " _
& NumberToText(n mod 1000000000)
End Select
End Function
Here is the code in c#
public static string AmountInWords(double amount)
{
var n = (int)amount;
if (n == 0)
return "";
else if (n > 0 && n <= 19)
{
var arr = new string[] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
return arr[n - 1] + " ";
}
else if (n >= 20 && n <= 99)
{
var arr = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
return arr[n / 10 - 2] + " " + AmountInWords(n % 10);
}
else if (n >= 100 && n <= 199)
{
return "One Hundred " + AmountInWords(n % 100);
}
else if (n >= 200 && n <= 999)
{
return AmountInWords(n / 100) + "Hundred " + AmountInWords(n % 100);
}
else if (n >= 1000 && n <= 1999)
{
return "One Thousand " + AmountInWords(n % 1000);
}
else if (n >= 2000 && n <= 999999)
{
return AmountInWords(n / 1000) + "Thousand " + AmountInWords(n % 1000);
}
else if (n >= 1000000 && n <= 1999999)
{
return "One Million " + AmountInWords(n % 1000000);
}
else if (n >= 1000000 && n <= 999999999)
{
return AmountInWords(n / 1000000) + "Million " + AmountInWords(n % 1000000);
}
else if (n >= 1000000000 && n <= 1999999999)
{
return "One Billion " + AmountInWords(n % 1000000000);
}
else
{
return AmountInWords(n / 1000000000) + "Billion " + AmountInWords(n % 1000000000);
}
}
why massive lookup table?
string GetWrittenInteger(int n)
{
string[] a = new string[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }
string[] b = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }
string[] c = new string[] {"Twenty", "Thirty", "Forty", "Sixty", "Seventy", "Eighty", "Ninety"};
string[] d = new string[] {"Hundred", "Thousand", "Million"}
string s = n.ToString();
for (int i = 0; i < s.Length; i++)
{
// logic (too lazy but you get the idea)
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace tryingstartfror4digits
{
class Program
{
static void Main(string[] args)
{
Program pg = new Program();
Console.WriteLine("Enter ur number");
int num = Convert.ToInt32(Console.ReadLine());
if (num <= 19)
{
string g = pg.first(num);
Console.WriteLine("The number is " + g);
}
else if ((num >= 20) && (num <= 99))
{
if (num % 10 == 0)
{
string g = pg.second(num / 10);
Console.WriteLine("The number is " + g);
}
else
{
string g = pg.second(num / 10) + pg.first(num % 10);
Console.WriteLine("The number is " + g);
}
}
else if ((num >= 100) && (num <= 999))
{
int k = num % 100;
string g = pg.first(num / 100) +pg.third(0) + pg.second(k / 10)+pg.first(k%10);
Console.WriteLine("The number is " + g);
}
else if ((num >= 1000) && (num <= 19999))
{
int h = num % 1000;
int k = h % 100;
string g = pg.first(num / 1000) + "Thousand " + pg.first(h/ 100) + pg.third(k) + pg.second(k / 10) + pg.first(k % 10);
Console.WriteLine("The number is " + g);
}
Console.ReadLine();
}
public string first(int num)
{
string name;
if (num == 0)
{
name = " ";
}
else
{
string[] arr1 = new string[] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" , "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
name = arr1[num - 1];
}
return name;
}
public string second(int num)
{
string name;
if ((num == 0)||(num==1))
{
name = " ";
}
else
{
string[] arr1 = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
name = arr1[num - 2];
}
return name;
}
public string third(int num)
{
string name ;
if (num == 0)
{
name = "";
}
else
{
string[] arr1 = new string[] { "Hundred" };
name = arr1[0];
}
return name;
}
}
}
this works fine from 1 to 19999 will update soon after i complete it
The accepted answer doesn't seem to work perfectly. It doesn't handle dashes in numbers like twenty-one, it doesn't put the word "and" in for numbers like "one hundred and one", and, well, it is recursive.
Here is my shot at the answer. It adds the "and" word intelligently, and hyphenates numbers appropriately. Let me know if any modifications are needed.
Here is how to call it (obviously you will want to put this in a class somewhere):
for (int i = int.MinValue+1; i < int.MaxValue; i++)
{
Console.WriteLine(ToWords(i));
}
Here is the code:
private static readonly string[] Ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
private static readonly string[] Teens =
{
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen"
};
private static readonly string[] Tens =
{
"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty",
"Ninety"
};
public static string ToWords(int number)
{
if (number == 0)
return "Zero";
var wordsList = new List<string>();
if (number < 0)
{
wordsList.Add("Negative");
number = Math.Abs(number);
}
if (number >= 1000000000 && number <= int.MaxValue) //billions
{
int billionsValue = number / 1000000000;
GetValuesUnder1000(billionsValue, wordsList);
wordsList.Add("Billion");
number -= billionsValue * 1000000000;
if (number > 0 && number < 10)
wordsList.Add("and");
}
if (number >= 1000000 && number < 1000000000) //millions
{
int millionsValue = number / 1000000;
GetValuesUnder1000(millionsValue, wordsList);
wordsList.Add("Million");
number -= millionsValue * 1000000;
if (number > 0 && number < 10)
wordsList.Add("and");
}
if (number >= 1000 && number < 1000000) //thousands
{
int thousandsValue = number/1000;
GetValuesUnder1000(thousandsValue, wordsList);
wordsList.Add("Thousand");
number -= thousandsValue * 1000;
if (number > 0 && number < 10)
wordsList.Add("and");
}
GetValuesUnder1000(number, wordsList);
return string.Join(" ", wordsList);
}
private static void GetValuesUnder1000(int number, List<string> wordsList)
{
while (number != 0)
{
if (number < 10)
{
wordsList.Add(Ones[number]);
number -= number;
}
else if (number < 20)
{
wordsList.Add(Teens[number - 10]);
number -= number;
}
else if (number < 100)
{
int tensValue = ((int) (number/10))*10;
int onesValue = number - tensValue;
if (onesValue == 0)
{
wordsList.Add(Tens[tensValue/10]);
}
else
{
wordsList.Add(Tens[tensValue/10] + "-" + Ones[onesValue]);
}
number -= tensValue;
number -= onesValue;
}
else if (number < 1000)
{
int hundredsValue = ((int) (number/100))*100;
wordsList.Add(Ones[hundredsValue/100]);
wordsList.Add("Hundred");
number -= hundredsValue;
if (number > 0)
wordsList.Add("and");
}
}
}
Here is a C# Console Application that will return whole numbers as well as decimals.
Just for Turkish representation of the class HumanFriendlyInteger (↑) (Türkçe, sayı yazı karşılığı):
public static class HumanFriendlyInteger
{
static string[] ones = new string[] { "", "Bir", "İki", "Üç", "Dört", "Beş", "Altı", "Yedi", "Sekiz", "Dokuz" };
static string[] teens = new string[] { "On", "On Bir", "On İki", "On Üç", "On Dört", "On Beş", "On Altı", "On Yedi", "On Sekiz", "On Dokuz" };
static string[] tens = new string[] { "Yirmi", "Otuz", "Kırk", "Elli", "Altmış", "Yetmiş", "Seksen", "Doksan" };
static string[] thousandsGroups = { "", " Bin", " Milyon", " Milyar" };
private static string FriendlyInteger(int n, string leftDigits, int thousands)
{
if (n == 0)
{
return leftDigits;
}
string friendlyInt = leftDigits;
if (friendlyInt.Length > 0)
{
friendlyInt += " ";
}
if (n < 10)
friendlyInt += ones[n];
else if (n < 20)
friendlyInt += teens[n - 10];
else if (n < 100)
friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0);
else if (n < 1000)
friendlyInt += FriendlyInteger(n % 100, ((n / 100 == 1 ? "" : ones[n / 100] + " ") + "Yüz"), 0); // Yüz 1 ile başlangıçta "Bir" kelimesini Türkçe'de almaz.
else
friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, "", thousands + 1), 0);
return friendlyInt + thousandsGroups[thousands];
}
public static string IntegerToWritten(int n)
{
if (n == 0)
return "Sıfır";
else if (n < 0)
return "Eksi " + IntegerToWritten(-n);
return FriendlyInteger(n, "", 0);
}
An extension of Nick Masao's answer for Bengali Numeric of same problem. Inital input of number is in Unicode string. Cheers!!
string number = "২২৮৯";
number = number.Replace("০", "0").Replace("১", "1").Replace("২", "2").Replace("৩", "3").Replace("৪", "4").Replace("৫", "5").Replace("৬", "6").Replace("৭", "7").Replace("৮", "8").Replace("৯", "9");
double vtempdbl = Convert.ToDouble(number);
string amount = AmountInWords(vtempdbl);
private static string AmountInWords(double amount)
{
var n = (int)amount;
if (n == 0)
return " ";
else if (n > 0 && n <= 99)
{
var arr = new string[] { "এক", "দুই", "তিন", "চার", "পাঁচ", "ছয়", "সাত", "আট", "নয়", "দশ", "এগার", "বারো", "তের", "চৌদ্দ", "পনের", "ষোল", "সতের", "আঠার", "ঊনিশ", "বিশ", "একুশ", "বাইস", "তেইশ", "চব্বিশ", "পঁচিশ", "ছাব্বিশ", "সাতাশ", "আঠাশ", "ঊনত্রিশ", "ত্রিশ", "একত্রিস", "বত্রিশ", "তেত্রিশ", "চৌত্রিশ", "পঁয়ত্রিশ", "ছত্রিশ", "সাঁইত্রিশ", "আটত্রিশ", "ঊনচল্লিশ", "চল্লিশ", "একচল্লিশ", "বিয়াল্লিশ", "তেতাল্লিশ", "চুয়াল্লিশ", "পয়তাল্লিশ", "ছিচল্লিশ", "সাতচল্লিশ", "আতচল্লিশ", "উনপঞ্চাশ", "পঞ্চাশ", "একান্ন", "বায়ান্ন", "তিপ্পান্ন", "চুয়ান্ন", "পঞ্চান্ন", "ছাপ্পান্ন", "সাতান্ন", "আটান্ন", "উনষাট", "ষাট", "একষট্টি", "বাষট্টি", "তেষট্টি", "চৌষট্টি", "পয়ষট্টি", "ছিষট্টি", " সাতষট্টি", "আটষট্টি", "ঊনসত্তর ", "সত্তর", "একাত্তর ", "বাহাত্তর", "তেহাত্তর", "চুয়াত্তর", "পঁচাত্তর", "ছিয়াত্তর", "সাতাত্তর", "আটাত্তর", "ঊনাশি", "আশি", "একাশি", "বিরাশি", "তিরাশি", "চুরাশি", "পঁচাশি", "ছিয়াশি", "সাতাশি", "আটাশি", "উননব্বই", "নব্বই", "একানব্বই", "বিরানব্বই", "তিরানব্বই", "চুরানব্বই", "পঁচানব্বই ", "ছিয়ানব্বই ", "সাতানব্বই", "আটানব্বই", "নিরানব্বই" };
return arr[n - 1] + " ";
}
else if (n >= 100 && n <= 199)
{
return AmountInWords(n / 100) + "এক শত " + AmountInWords(n % 100);
}
else if (n >= 100 && n <= 999)
{
return AmountInWords(n / 100) + "শত " + AmountInWords(n % 100);
}
else if (n >= 1000 && n <= 1999)
{
return "এক হাজার " + AmountInWords(n % 1000);
}
else if (n >= 1000 && n <= 99999)
{
return AmountInWords(n / 1000) + "হাজার " + AmountInWords(n % 1000);
}
else if (n >= 100000 && n <= 199999)
{
return "এক লাখ " + AmountInWords(n % 100000);
}
else if (n >= 100000 && n <= 9999999)
{
return AmountInWords(n / 100000) + "লাখ " + AmountInWords(n % 100000);
}
else if (n >= 10000000 && n <= 19999999)
{
return "এক কোটি " + AmountInWords(n % 10000000);
}
else
{
return AmountInWords(n / 10000000) + "কোটি " + AmountInWords(n % 10000000);
}
}
The following C# console app code will accepts a monetary value in numbers up to 2 decimals and prints it in English. This not only converts integer to its English equivalent but as a monetary value in dollars and cents.
namespace ConsoleApplication2
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
bool repeat = true;
while (repeat)
{
string inputMonetaryValueInNumberic = string.Empty;
string centPart = string.Empty;
string dollarPart = string.Empty;
Console.Write("\nEnter the monetary value : ");
inputMonetaryValueInNumberic = Console.ReadLine();
inputMonetaryValueInNumberic = inputMonetaryValueInNumberic.TrimStart('0');
if (ValidateInput(inputMonetaryValueInNumberic))
{
if (inputMonetaryValueInNumberic.Contains('.'))
{
centPart = ProcessCents(inputMonetaryValueInNumberic.Substring(inputMonetaryValueInNumberic.IndexOf(".") + 1));
dollarPart = ProcessDollar(inputMonetaryValueInNumberic.Substring(0, inputMonetaryValueInNumberic.IndexOf(".")));
}
else
{
dollarPart = ProcessDollar(inputMonetaryValueInNumberic);
}
centPart = string.IsNullOrWhiteSpace(centPart) ? string.Empty : " and " + centPart;
Console.WriteLine(string.Format("\n\n{0}{1}", dollarPart, centPart));
}
else
{
Console.WriteLine("Invalid Input..");
}
Console.WriteLine("\n\nPress any key to continue or Escape of close : ");
var loop = Console.ReadKey();
repeat = !loop.Key.ToString().Contains("Escape");
Console.Clear();
}
}
private static string ProcessCents(string cents)
{
string english = string.Empty;
string dig3 = Process3Digit(cents);
if (!string.IsNullOrWhiteSpace(dig3))
{
dig3 = string.Format("{0} {1}", dig3, GetSections(0));
}
english = dig3 + english;
return english;
}
private static string ProcessDollar(string dollar)
{
string english = string.Empty;
foreach (var item in Get3DigitList(dollar))
{
string dig3 = Process3Digit(item.Value);
if (!string.IsNullOrWhiteSpace(dig3))
{
dig3 = string.Format("{0} {1}", dig3, GetSections(item.Key));
}
english = dig3 + english;
}
return english;
}
private static string Process3Digit(string digit3)
{
string result = string.Empty;
if (Convert.ToInt32(digit3) != 0)
{
int place = 0;
Stack<string> monetaryValue = new Stack<string>();
for (int i = digit3.Length - 1; i >= 0; i--)
{
place += 1;
string stringValue = string.Empty;
switch (place)
{
case 1:
stringValue = GetOnes(digit3[i].ToString());
break;
case 2:
int tens = Convert.ToInt32(digit3[i]);
if (tens == 1)
{
if (monetaryValue.Count > 0)
{
monetaryValue.Pop();
}
stringValue = GetTens((digit3[i].ToString() + digit3[i + 1].ToString()));
}
else
{
stringValue = GetTens(digit3[i].ToString());
}
break;
case 3:
stringValue = GetOnes(digit3[i].ToString());
if (!string.IsNullOrWhiteSpace(stringValue))
{
string postFixWith = " Hundred";
if (monetaryValue.Count > 0)
{
postFixWith = postFixWith + " And";
}
stringValue += postFixWith;
}
break;
}
if (!string.IsNullOrWhiteSpace(stringValue))
monetaryValue.Push(stringValue);
}
while (monetaryValue.Count > 0)
{
result += " " + monetaryValue.Pop().ToString().Trim();
}
}
return result;
}
private static Dictionary<int, string> Get3DigitList(string monetaryValueInNumberic)
{
Dictionary<int, string> hundredsStack = new Dictionary<int, string>();
int counter = 0;
while (monetaryValueInNumberic.Length >= 3)
{
string digit3 = monetaryValueInNumberic.Substring(monetaryValueInNumberic.Length - 3, 3);
monetaryValueInNumberic = monetaryValueInNumberic.Substring(0, monetaryValueInNumberic.Length - 3);
hundredsStack.Add(++counter, digit3);
}
if (monetaryValueInNumberic.Length != 0)
hundredsStack.Add(++counter, monetaryValueInNumberic);
return hundredsStack;
}
private static string GetTens(string tensPlaceValue)
{
string englishEquvalent = string.Empty;
int value = Convert.ToInt32(tensPlaceValue);
Dictionary<int, string> tens = new Dictionary<int, string>();
tens.Add(2, "Twenty");
tens.Add(3, "Thirty");
tens.Add(4, "Forty");
tens.Add(5, "Fifty");
tens.Add(6, "Sixty");
tens.Add(7, "Seventy");
tens.Add(8, "Eighty");
tens.Add(9, "Ninty");
tens.Add(10, "Ten");
tens.Add(11, "Eleven");
tens.Add(12, "Twelve");
tens.Add(13, "Thrteen");
tens.Add(14, "Fourteen");
tens.Add(15, "Fifteen");
tens.Add(16, "Sixteen");
tens.Add(17, "Seventeen");
tens.Add(18, "Eighteen");
tens.Add(19, "Ninteen");
if (tens.ContainsKey(value))
{
englishEquvalent = tens[value];
}
return englishEquvalent;
}
private static string GetOnes(string onesPlaceValue)
{
int value = Convert.ToInt32(onesPlaceValue);
string englishEquvalent = string.Empty;
Dictionary<int, string> ones = new Dictionary<int, string>();
ones.Add(1, " One");
ones.Add(2, " Two");
ones.Add(3, " Three");
ones.Add(4, " Four");
ones.Add(5, " Five");
ones.Add(6, " Six");
ones.Add(7, " Seven");
ones.Add(8, " Eight");
ones.Add(9, " Nine");
if (ones.ContainsKey(value))
{
englishEquvalent = ones[value];
}
return englishEquvalent;
}
private static string GetSections(int section)
{
string sectionName = string.Empty;
switch (section)
{
case 0:
sectionName = "Cents";
break;
case 1:
sectionName = "Dollars";
break;
case 2:
sectionName = "Thousand";
break;
case 3:
sectionName = "Million";
break;
case 4:
sectionName = "Billion";
break;
case 5:
sectionName = "Trillion";
break;
case 6:
sectionName = "Zillion";
break;
}
return sectionName;
}
private static bool ValidateInput(string input)
{
return Regex.IsMatch(input, "[0-9]{1,18}(\\.[0-9]{1,2})?"))
}
}
}
Just get that string and convert with the
like as
string s = txtNumber.Text.Tostring();
int i = Convert.ToInt32(s.Tostring());
It will write only full integer value