How to convert a numeric value into English words in ASP.NET
using c#/VB.NET.
ASP.NET:
C#:
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using
System.Web.UI.WebControls;
public partial class ConvertNumbersToWords : System.Web.UI.Page
{
public
static string
NumberToWords(Int64 num)
{
if (num == 0)
return "Zero";
if (num < 0)
return "Minus
" + NumberToWords(Math.Abs(num));
string words = "";
if ((num / 1000000) > 0)
{
words +=
NumberToWords(num / 1000000) + " Million
";
num %= 1000000;
}
if ((num / 1000) > 0)
{
words +=
NumberToWords(num / 1000) + " thousand
";
num %= 1000;
}
if ((num / 100) > 0)
{
words +=
NumberToWords(num / 100) + " hundred ";
num %= 100;
}
if (num > 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 (num < 20)
words +=
unitsMap[num];
else
{
words +=
tensMap[num / 10];
if ((num % 10) > 0)
words += "-"
+ unitsMap[num % 10];
}
}
return words;
}
protected
void Button1_Click(object
sender, EventArgs e)
{
String word = NumberToWords(Convert.ToInt64(txtNum.Text));
Response.Write(word);
}
}
|
In VB.NET:
Imports
System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports
System.Web.UI.WebControls
Partial Public Class ConvertNumbersToWords
Inherits
System.Web.UI.Page
Public
Shared Function
NumberToWords(ByVal num As Int64) As String
If num = 0 Then
Return "Zero"
End If
If num < 0 Then
Return "Minus
" & NumberToWords(Math.Abs(num))
End If
Dim words As String = ""
If (num \ 1000000) > 0 Then
words +=
NumberToWords(num \ 1000000) & " Million
"
num = num Mod 1000000
End If
If (num \ 1000) > 0 Then
words +=
NumberToWords(num \ 1000) & " thousand
"
num = num Mod 1000
End If
If (num \ 100) > 0 Then
words +=
NumberToWords(num \ 100) & " hundred
"
num = num Mod 100
End If
If num > 0 Then
If words <> ""
Then
words += "and "
End If
Dim unitsMap = New
() {"zero", "one", "two",
"three", "four", "five",
_
"six", "seven",
"eight", "nine", "ten",
"eleven", _
"twelve", "thirteen",
"fourteen", "fifteen", "sixteen",
"seventeen", _
"eighteen", "nineteen"}
Dim
tensMap = New () {"zero",
"ten", "twenty",
"thirty", "forty", "fifty",
_
"sixty", "seventy",
"eighty", "ninety"}
If num < 20 Then
words +=
unitsMap(num)
Else
words +=
tensMap(num \ 10)
If (num Mod 10)
> 0 Then
words += "-" & unitsMap(num Mod 10)
End If
End If
End If
Return words
End
Function
Protected
Sub Button1_Click(ByVal
sender As Object,
ByVal e As EventArgs)
Dim word As [String] = NumberToWords(Convert.ToInt64(txtNum.Text))
Response.Write(word)
End
Sub
End Class
|
Output:
No comments:
Post a Comment