The
purpose of this article is to make beginners to understand practical use of
recursion in ASP.NET (c#.net). I have taken a practical scenario which occurs widely
in most of the applications. Hence I have come up with code for converting a
number into Indian Rupees.
Here
is a function “ConvertToWords” recursively called since same notation applies
for digits in Thousands, Lakhs and Crores place in number once number crosses 999.
using System;
namespace NumberConvertor.Models
{
public class NumberConverter
{
public static string ConvertToWords(double num,bool appendCurrency=true)
{
string[] tens = new string[] { "Ten", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
string[] ones = new string[] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen" };
string result = "";
//Finding
Number of Crores in a given number
int noOfCrores = ((int)num) / 10000000;
if (noOfCrores > 0) result += ones[noOfCrores] +" Crore ";
num-= 10000000 * noOfCrores;
//Finding
Number of lakhs in a given number
int noOfLakhs = ((int)num) / 100000;
if (noOfLakhs > 0) result += ConvertToWords(noOfLakhs,false) + " Lakh ";
num -= noOfLakhs * 100000;
//Finding
Number of thousands in a given number
int noOfThousands=((int)num)/1000;
if (noOfThousands > 0) result +=
ConvertToWords(noOfThousands,false) + " Thounsand ";
num -= noOfThousands * 1000;
//Finding
Number of hundreds in a given number
int noOfHundreds = (int)num / 100;
if (noOfHundreds > 0) result += ones[noOfHundreds - 1] + " Hundred ";
num -= noOfHundreds * 100;
if (num < 20)
result += ones[(int)num - 1];
else
result += tens[((int)num / 10) - 1] + " "+ones[(int)num % 10 - 1];
if (appendCurrency) result += "
Rupees";
//extract
digits after decimal point
num = (int)(Math.Round((num - (int)num) * 100));
if (num > 0)
{
result +=" "+
ConvertToWords(num,false);
if (appendCurrency) result += "
Paise";
}
return result;
}
}
}
No comments:
Post a Comment