B4J Code Snippet [B4X] Integer to Word

B4X:
' Convert an integer number to words
' Pr.S
' Range: >-1,000,000 to <1,000,000 (One Million).
' Writing bank checks from a currency amount Example: For $123.45 ---> "$ " & Int2Word(123, False, False) & " and 45/100"
'    Dim d() As Double = Array As Double(32.88, 8555.71, 3.04, 17.30, 83888.22)
'    For Each dtst As Double In d
'        Dim integer As String = Regex.Split("\.",dtst)(0)
'        Dim fraction As String = Regex.Split("\.",dtst)(1)
'        Log(dtst &" - "& Int2Word(integer, False, False) &" and " & fraction &"/100")
'    Next
' Negatives Example: For -13422 ---> Int2Word(-13422, False, True)
Sub Int2Word (Value As Int, IgnoreZero As Boolean, AllowNegatives As Boolean) As String
    Dim OnWords() As String = Array As String("Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen")
    Dim TyWords() As String = Array As String("","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety")

    Dim rs As String
    Dim Prefix As String

    ' Deal with Negatives
    If Value < 0 And AllowNegatives = False Then Return ""
    If Value < 0 Then
        Prefix = "Negative "
        Value = Value * -1
    End If

    Dim s As String = Value
    
    If Value < 20 Then
        If (Value = 0 And IgnoreZero = False) Or Value > 0 Then
            rs = OnWords(Value)
        End If
    End If
    If Value >= 20 And Value < 100 Then
        rs = (TyWords(s.SubString2(0,1)) &" "& Int2Word(s.SubString(1), True, AllowNegatives))
    End If
    If Value >= 100 And Value < 1000 Then
        rs = (Int2Word(s.SubString2(0,1), True, False) &" Hundred "& Int2Word(s.SubString(1), True, False))
    End If
    If Value >= 1000 And Value < 10000 Then
        rs = (Int2Word(s.SubString2(0,1), True, False) &" Thousand "& Int2Word(s.SubString(1), True, False))
    End If
    If Value >= 10000 And Value < 100000 Then
        rs = (Int2Word(s.SubString2(0,2), True, False) &" Thousand "& Int2Word(s.SubString(2), True, False))
    End If
    If Value >= 100000 And Value < 1000000 Then
        rs = (Int2Word(s.SubString2(0,3), True, False) &" Thousand "& Int2Word(s.SubString(3), True, False))
    End If

    Return Prefix & rs
End Sub
 
Top