Pages

Thursday, August 26, 2010

Number to Words

Most accounting softwares or many small utilities requires a function which can convert a number into words.

Here is a function which can convert a number logically upto 9,99,99,99,999 but restricted by Integer.MaxValue that is 2,14,74,83,647.


  Private dict As New Dictionary(Of Integer, String)
  Private amount(,) As Object = {{0, "Zero"}, {1, "One"}, {2, "Two"}, {3, "Three"}, {4, "Four"}, {5, "Five"}, {6, "Six"}, {7, "Seven"}, {8, "Eight"}, {9, "Nine"}, {10, "Ten"}, {11, "Eleven"}, {12, "Twelve"}, {13, "Thirteen"}, {14, "Fourteen"}, {15, "Fifteen"}, {16, "Sixteen"}, {17, "Seventeen"}, {18, "Eighteen"}, {19, "Nineteen"}, {20, "Twenty"}, {30, "Thirty"}, {40, "Forty"}, {50, "Fifty"}, {60, "Sixty"}, {70, "Seventy"}, {80, "Eighty"}, {90, "Ninety"}, {100, "Hundred"}, {1000, "Thousand"}, {100000, "Lakh"}, {10000000, "Crore"}, {1000000000, "Arab"}}

  Public Function NumberToWords(ByVal Number As Decimal) As String
    If dict.Count = 0 Then
      For i As Integer = 0 To UBound(amount, 1)
        dict.Add(amount(i, 0), amount(i, 1))
      Next
    End If

    Dim InWordsFull As String = ""
    Dim InWordsDec As String = ""
    Dim DecimalPart As Decimal = Number - Math.Floor(Number)
    Dim FullPart As Integer = Number - DecimalPart
    If DecimalPart <> 0 Then
      DecimalPart = CDec(DecimalPart.ToString.Replace("0.", ""))
    End If

    While FullPart <> 0
      For i As Integer = UBound(amount, 1) To 0 Step -1
        If amount(i, 0) <= FullPart Then
          Dim temp As Integer = Math.Floor(FullPart / amount(i, 0))
          InWordsFull &= IIf(i > 27, convert(temp) & " ", "") & dict(amount(i, 0)) & " "
          FullPart -= temp * amount(i, 0)
          Exit For
        End If
      Next
    End While

    While DecimalPart <> 0
      For i As Integer = UBound(amount, 1) To 0 Step -1
        If amount(i, 0) <= DecimalPart Then
          Dim temp As Integer = Math.Floor(DecimalPart / amount(i, 0))
          InWordsDec &= IIf(i > 27, convert(temp) & " ", "") & dict(amount(i, 0)) & " "
          DecimalPart -= temp * amount(i, 0)
          Exit For
        End If
      Next
    End While

    Return InWordsFull.Trim & IIf(InWordsDec <> "", " Point " & InWordsDec.Trim, "")
  End Function

  Private Function convert(ByVal number As Integer) As String
    Dim InWords As String = ""
    If dict.ContainsKey(number) Then
      InWords = dict(number)
    Else
      While number <> 0
        For i As Integer = UBound(amount, 1) To 0 Step -1
          If amount(i, 0) <= number Then
            Dim temp As Integer = Math.Floor(number / amount(i, 0))
            InWords &= IIf(i > 27, dict(temp) & " ", "") & dict(amount(i, 0)) & " "
            number -= temp * amount(i, 0)
            Exit For
          End If
        Next
      End While
    End If

    Return InWords.Trim
  End Function

No comments: