Public Function AmountInWords(ByVal nAmount As String,可选ByVal wAmount _ As String = vbNullString,Optional ByVal nSet As Object = Nothing)As String '我们确保输入的值是数字 如果不是IsNumeric(nAmount)则返回“请仅输入数值。”
Dim tempDecValue As String = String.Empty : If InStr(nAmount, ".") Then _
tempDecValue = nAmount.Substring(nAmount.IndexOf("."))
nAmount = Replace(nAmount, tempDecValue, String.Empty)
Try
Dim intAmount As Long = nAmount
If intAmount > 0 Then
nSet = IIf((intAmount.ToString.Trim.Length / 3) _
> (CLng(intAmount.ToString.Trim.Length / 3)), _
CLng(intAmount.ToString.Trim.Length / 3) + 1, _
CLng(intAmount.ToString.Trim.Length / 3))
Dim eAmount As Long = Microsoft.VisualBasic.Left(intAmount.ToString.Trim, _
(intAmount.ToString.Trim.Length - ((nSet - 1) * 3)))
Dim multiplier As Long = 10 ^ (((nSet - 1) * 3))
Dim Ones() As String = _
{"", "One", "Two", "Three", _
"Four", "Five", _
"Six", "Seven", "Eight", "Nine"}
Dim Teens() As String = {"", _
"Eleven", "Twelve", "Thirteen", _
"Fourteen", "Fifteen", _
"Sixteen", "Seventeen", "Eighteen", "Nineteen"}
Dim Tens() As String = {"", "Ten", _
"Twenty", "Thirty", _
"Forty", "Fifty", "Sixty", _
"Seventy", "Eighty", "Ninety"}
Dim HMBT() As String = {"", "", _
"Thousand", "Million", _
"Billion", "Trillion", _
"Quadrillion", "Quintillion"}
intAmount = eAmount
Dim nHundred As Integer = intAmount \ 100 : intAmount = intAmount Mod 100
Dim nTen As Integer = intAmount \ 10 : intAmount = intAmount Mod 10
Dim nOne As Integer = intAmount \ 1
If nHundred > 0 Then wAmount = wAmount & _
Ones(nHundred) & " Hundred " 'This is for hundreds
If nTen > 0 Then 'This is for tens and teens
If nTen = 1 And nOne > 0 Then 'This is for teens
wAmount = wAmount & Teens(nOne) & " "
Else 'This is for tens, 10 to 90
wAmount = wAmount & Tens(nTen) & IIf(nOne > 0, "-", " ")
If nOne > 0 Then wAmount = wAmount & Ones(nOne) & " "
End If
Else 'This is for ones, 1 to 9
If nOne > 0 Then wAmount = wAmount & Ones(nOne) & " "
End If
wAmount = wAmount & HMBT(nSet) & " "
wAmount = AmountInWords(CStr(CLng(nAmount) - _
(eAmount * multiplier)).Trim & tempDecValue, wAmount, nSet - 1)
Else
If Val(nAmount) = 0 Then nAmount = nAmount & _
tempDecValue : tempDecValue = String.Empty
If (Math.Round(Val(nAmount), 2) * 100) > 0 Then wAmount = _
Trim(AmountInWords(CStr(Math.Round(Val(nAmount), 2) * 100), _
wAmount.Trim & " And ", 1)) & " Cents"
End If
Catch ex As Exception
'MessageBox.Show(“遇到错误:”& ex.Message,_ '“将数字转换为单词”,_ 'MessageBoxButtons.OK,MessageBoxIcon.Error) '返回'!#ERROR_ENCOUNTERED“ 结束尝试
'Trap null values
If IsNothing(wAmount) = True Then wAmount = String.Empty Else wAmount = _
IIf(InStr(wAmount.Trim.ToLower, ""), _
wAmount.Trim, wAmount.Trim & " ")
'Display the result
Return wAmount
结束功能
这是我的代码但是当我得到小数点的.00时,我希望它应该打印零美分
答案 0 :(得分:0)
您检查是否nAmount > 0
,但不检查是否nAmount = 0
。
If nAmount = 0 then wAnount = "Zero"
因为你正在寻找美元和美分 - 这是两个单独的数字连接成一个字符串,用于人类可读性目的。因此,不是试图在一个函数中写入整个批次,而是将其调用两次,一次用于美元部分,然后一次用于美分部分。这使您可以灵活地提供“零美元和零分数”的答案。这也将为您提供更高效的函数代码。
您也不会检查是否nAmount < 0
。那你做什么?