Tuesday, March 19, 2013

Tcl Proc To Convert A Number To Words


# Does not like 0 as its argument
# Handles well beyond 1,76,000 Crores :-)
# Modified from: Cognitive Pabulum

proc inwords {n} {
    array set ones { 0 "" 1 One 2 Two 3 Three 4 Four 5 Five 6 Six 7 Seven 8 Eight 9 Nine }
    array set teens {
        10 Ten 11 Eleven 12 Twelve 13 Thirteen 14 Fourteen 15 Fifteen
        16 Sixteen 17 Seventeen 18 Eighteen 19 Nineteen
    }
    array set tens { 2 Twenty 3 Thirty 4 Fourty 5 Fifty 6 Sixty 7 Seventy 8 Eighty 9 Ninety }

    if {[expr $n / 10] == 0} {
        return $ones($n)
    } elseif {[expr $n / 100] == 0} {
        if {[expr [expr $n / 10] % 10] == 1} {
            return $teens($n)
        } else {
            return "$tens([expr $n/10]) $ones([expr $n % 10])"
        }
    } elseif {[expr $n / 1000] == 0} {
        return "[inwords [expr $n / 100]] Hundred [inwords [expr $n % 100]]"
    } elseif {[expr $n / 100000] == 0} {
        return "[inwords [expr $n / 1000]] Thousand [inwords [expr $n % 1000]]"
    } elseif {[expr $n / 10000000] == 0} {
        return "[inwords [expr $n / 100000]] Lakh [inwords [expr $n % 100000]]"
    } else {
        return "[inwords [expr $n / 10000000]] Crore [inwords [expr $n % 10000000]]"
    }
}


puts "67543: [inwords 67543]"
puts "67500: [inwords 67500]"
puts "15500: [inwords 15500]"
puts "17001: [inwords 17001]"
puts "1000: [inwords 1000]"
puts "999999: [inwords 999999]"
puts "9999999: [inwords 9999999]"
puts "99999999: [inwords 99999999]"
puts "999999999: [inwords 999999999]"
puts "9999999999: [inwords 9999999999]"
puts "99999999999: [inwords 99999999999]"
puts "999999999999: [inwords 999999999999]"
puts "9999999999999: [inwords 9999999999999]"
puts "1760000000000: [inwords 1760000000000]"

Output:


67543: Sixty Seven Thousand Five Hundred Fourty Three
67500: Sixty Seven Thousand Five Hundred
15500: Fifteen Thousand Five Hundred
17001: Seventeen Thousand One
1000: One Thousand
999999: Nine Lakh Ninety Nine Thousand Nine Hundred Ninety Nine
9999999: Ninety Nine Lakh Ninety Nine Thousand Nine Hundred Ninety Nine
99999999: Nine Crore Ninety Nine Lakh Ninety Nine Thousand Nine Hundred Ninety Nine
999999999: Ninety Nine Crore Ninety Nine Lakh Ninety Nine Thousand Nine Hundred Ninety Nine
9999999999: Nine Hundred Ninety Nine Crore Ninety Nine Lakh Ninety Nine Thousand Nine Hundred Ninety Nine
99999999999: Nine Thousand Nine Hundred Ninety Nine Crore Ninety Nine Lakh Ninety Nine Thousand Nine Hundred Ninety Nine
999999999999: Ninety Nine Thousand Nine Hundred Ninety Nine Crore Ninety Nine Lakh Ninety Nine Thousand Nine Hundred Ninety Nine
9999999999999: Nine Lakh Ninety Nine Thousand Nine Hundred Ninety Nine Crore Ninety Nine Lakh Ninety Nine Thousand Nine Hundred Ninety Nine
1760000000000: One Lakh Seventy Six Thousand  Crore

No comments:

Post a Comment