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?
Type the formula =SpellNumber(A1) into the cell where you want to display a written number, where A1 is the cell containing the number you want to convert. You can also manually type the value like =SpellNumber(22.50).
Select the cells that have numbers stored as text. On the Home tab, click Paste > Paste Special. Click Multiply, and then click OK. Excel multiplies each cell by 1, and in doing so, converts the text to numbers.
Step 1 − Divide the decimal number to be converted by the value of the new base. Step 2 − Get the remainder from Step 1 as the rightmost digit (least significant digit) of new base number. Step 3 − Divide the quotient of the previous divide by the new base.
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á!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With