Introduction
This article explains how to convert a number into words using recursion. I am posting this article to help the developers in the situation where they need to convert an amount into words for reporting purposes and making data more informative. This article takes an amount or a number as input and converts it into words, as shown below.
Many times, while generating reports or logging/processing the data, there are situations when we need to show the numbers as words. This is a challenging task as no one would like to spend much time on writing code for this. In here, we will use recursion for the conversion.
Recursion
Here, I am writing a method which takes a number as input and returns the converted number as a string, as shown above.
This method is applicable to the numbers from 0 to 999999999. This method can be extended for a larger number as well by adding some if conditions and adding the values in unitsMap and tensMap array.
- private static string ConvertIntoWords(long number)
- {
- if (number == 0)
- return "zero";
- if (number < 0)
- return "minus " + ConvertIntoWords(Math.Abs(number));
- string words = "";
- if ((number / 10000000) > 0)
- {
- words += ConvertIntoWords(number / 10000000) + " crores ";
- number %= 10000000;
- }
- if ((number / 100000) > 0)
- {
- words += ConvertIntoWords(number / 100000) + " lacs ";
- number %= 100000;
- }
- if ((number / 1000) > 0)
- {
- words += ConvertIntoWords(number / 1000) + " thousand ";
- number %= 1000;
- }
- if ((number / 100) > 0)
- {
- words += ConvertIntoWords(number / 100) + " hundred ";
- number %= 100;
- }
- if (number > 0)
- {
- 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;
- }


SathishkumarPosted Dec 12, 2018, 6:54 AM
Really helpful bro, seeking a lot of sharing from you , Thanks a lot for your updates
SathishkumarPosted Dec 12, 2018, 6:53 AM
Really helpful bro. Thanks a lot.
Jeeva SubburajPosted Dec 11, 2018, 2:04 PM
Humanizr is one of most popular and .net foundation library which supports all needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities https://github.com/Humanizr/Humanizer#number-to-words
Rehman ShahidPosted Dec 11, 2018, 10:01 AM
Nice one...