Converting Numbers to Words – Shortest code in VB.Net

This is a sample code I wrote in VB.Net which can output any number to words. This is the best code you may find in the internet because it uses recursion, it is fast and uses less system resources.

I assume that you know VB.Net already. So, I am not going to explain the code line by line.

During form load it popupates the array “Arr( )”. After that, you just have to call NumToWords(<your_number_here>) and it will return a string as output.

You can use it in your software, use it as a macro in Excel or do whatever you want.

As any other code, it still has its limits. Please feel free to modify and edit code at your own risk.

Public Class Form1

    Dim Arr(100) As String

    Public Function NumToWords(ByVal Num As Long) As String

        Dim n As Long

        Dim s As String

        s = ""

        If Num = 0 Then

            NumToWords = "Zero"

            Exit Function

        End If

        n = Num

        If n >= 10000000 Then

            s = s & NumToWords(n \ 10000000) & " Crore "

            n = n Mod 10000000

        End If

        If n >= 100000 Then

            s = s & NumToWords(n \ 100000) & " Lakh "

            n = n Mod 100000

        End If

        If n >= 1000 Then

            s = s & NumToWords(n \ 1000) & " Thousand "

            n = n Mod 1000

        End If

        If n >= 100 Then

            s = s & Arr(n \ 100) & " Hundred "

            n = n Mod 100

        End If

        If n > 20 Then

            s = s & Arr((n \ 10) * 10) & " "

            n = n Mod 10

        End If

        If n <= 20 And n > 0 Then

            s = s & Arr(n)

        End If

        NumToWords = s

    End Function

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Arr(0) = "Zero"

        Arr(1) = "One"

        Arr(2) = "Two"

        Arr(3) = "Three"

        Arr(4) = "Four"

        Arr(5) = "Five"

        Arr(6) = "Six"

        Arr(7) = "Seven"

        Arr(8) = "Eight"

        Arr(9) = "Nine"

        Arr(10) = "Ten"

        Arr(11) = "Eleven"

        Arr(12) = "Twelve"

        Arr(13) = "Thirteen"

        Arr(14) = "Fourteen"

        Arr(15) = "Fifteen"

        Arr(16) = "Sixteen"

        Arr(17) = "Seventeen"

        Arr(18) = "Eighteen"

        Arr(19) = "Nineteen"

        Arr(20) = "Twenty"

        Arr(30) = "Thirty"

        Arr(40) = "Fourty"

        Arr(50) = "Fifty"

        Arr(60) = "Sixty"

        Arr(70) = "Seventy"

        Arr(80) = "Eighty"

        Arr(90) = "Ninety"

    End Sub

End Class

3053total visits,4visits today

Leave a Reply