How to Convert Number to Word in Asp.net



Here we will create number to word in dot net may be in some project or any other else purpose we need it. When we generate invoice at that time we need number to word.

For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label.

CODE:

<div>
       Enter Number : <asp:TextBox ID="TextBox1" runat="server"
            AutoPostBack="true" OnTextChanged="TextBox1_TextChanged" Width="265px"></asp:TextBox>
        <br />
        <asp:Label ID="Label2" runat="server"></asp:Label>
    </div>

CODE BEHIND:

protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                TextBox1.Text = "123456";
                decimal iAmt = Convert.ToDecimal(TextBox1.Text);
                string strAmount = wordify(iAmt);
                Label2.Text = strAmount;
            }        
        }
        static string wordify(decimal v)
        {
            if (v == 0) return "zero";
            var units = "|One|Two|Three|Four|Five|Six|Seven|Eight|Nine".Split('|');
            var teens = "|eleven|twelve|thir#|four#|fif#|six#|seven#|eigh#|nine#".Replace("#", "teen").Split('|');
            var tens = "|Ten|Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety".Split('|');
            var thou = "|Thousand|m#|b#|tr#|quadr#|quint#|sex#|sept#|oct#".Replace("#", "illion").Split('|');

            var g = v +" : "+"<style>" +
                    @"#Label2
                    {
                        background-color:Yellow;
                    }
                    </style>
                    ";
            var w = "";
            var p = 0;
            v = Math.Abs(v);
            while (v > 0)
            {
                int b = (int)(v % 1000);
                if (b > 0)
                {
                    var h = (b / 100);
                    var t = (b - h * 100) / 10;
                    var u = (b - h * 100 - t * 10);
                    var s = ((h > 0) ? units[h] + " Hundred" + ((t > 0 | u > 0) ? " and " : "") : "") + ((t > 0) ? (t == 1 && u > 0) ? teens[u] : tens[t] + ((u > 0) ? "-" : "") : "") + ((t != 1) ? units[u] : ""); s = (((v > 1000) && (h == 0) && (p == 0)) ? " and " : (v > 1000) ? ", " : "") + s; w = s + " " + thou[p] + w;
                } v = v / 1000; p++;
            }
            return g + w;
        }

        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            decimal iAmt = Convert.ToDecimal(TextBox1.Text);
            string strAmount = wordify(iAmt);
            Label2.Text = strAmount;
        }
Now check in your webpage and enter amount how many you want to convert in word.

Related Posts

Previous
Next Post »

Thanks for comments.....