Convert a number to words
Posted by
Carlo Linga
Here is a function that converts a given numeric value to words in dollars or other currency. You can use this for your check writing application where you need to put the dollar amount in words in your checks.
For example:
? InWords(1234567890123.45)
should return:
One Trillion Two Hundred Thirty Four Billion Five Hundred Sixty Seven Million Eight Hundred Ninety Thousand One Hundred Twenty Three And 45/100 Dollars Only
Here’s the code:
Public Function InWords(varAmount As Variant) As String
Dim strInWords As String
Dim decAmount As Variant
Dim intHundreds As Integer
Dim intDecimal As Integer
Dim strThou(5) As String
Dim ctr As Byte
' Value should be less than 10 Trillion
If varAmount > 9999999999999.99@ Then
InWords = "*** Value too large to convert ***"
Exit Function
Else
decAmount = CDec(varAmount)
End If
strThou(1) = ""
strThou(2) = " Thousand "
strThou(3) = " Million "
strThou(4) = " Billion "
strThou(5) = " Trillion "
intDecimal = CInt((decAmount - Int(decAmount)) * 100)
decAmount = Int(decAmount)
For ctr = 1 To 5
intHundreds = ((decAmount / 1000) - Int(decAmount / 1000)) * 1000
If intHundreds > 0 Then
strInWords = Hundreds(intHundreds) & strThou(ctr) & strInWords
End If
If decAmount >= 1 Then
decAmount = Int(decAmount / 1000)
Else
Exit For
End If
Next ctr
InWords = strInWords & " And " & intDecimal & "/100 Dollars Only"
End Function
Public Function Hundreds(intAmount As Integer) As String
Static varOnes As Variant
Static varTens As Variant
Dim strWords As String
Dim bOnes As Byte
Dim bTens As Byte
Dim bTeens As Byte
Dim bHundreds As Byte
If intAmount > 999 Then
Hundreds = "***Parameter should be less than 999***"
Exit Function
End If
If IsEmpty(varOnes) Then
varOnes = Array("", "One", "Two", "Three", "Four", "Five", _
"Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", _
"Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", _
"Eighteen", "Nineteen")
End If
If IsEmpty(varTens) Then
varTens = Array("", "Ten", "Twenty", "Thirty", "Forty", _
"Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End If
bHundreds = Int(intAmount / 100)
If bHundreds > 0 Then
strWords = varOnes(bHundreds) & " Hundred "
End If
bTeens = ((intAmount / 100) - Int(intAmount / 100)) * 100
If bTeens < 20 Then
strWords = strWords & varOnes(bTeens)
Else
bTens = Int(intAmount / 10) - (Int(intAmount / 100) * 10)
If bTens > 0 Then
strWords = strWords & varTens(bTens) & " "
End If
bOnes = intAmount - (Int(intAmount / 10) * 10)
If bOnes > 0 Then
strWords = strWords & varOnes(bOnes)
End If
End If
Hundreds = strWords
End Function
Subscribe to:
Post Comments (Atom)
Post a Comment