05 Jun 2010

Number to words converter - Indian style

The Indian numbering system is different from the standard three decimal western one. The divisions are thousand - lakh (100K) - crore (10M). Post crore, there are obscure divisions like “arab”, “kharab” that are rarely used.

I couldn’t find anything usable so I’ve written this small Python snippet for this conversion.

def number_to_words (n):
  words = ''

  units = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
  tens = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']

  for group in ['', 'hundred', 'thousand', 'lakh', 'crore']:

    if group in ['', 'thousand', 'lakh']:
      n, digits = n // 100, n % 100
    elif group == 'hundred':
      n, digits = n // 10, n % 10
    else:
      digits = n

    if digits in range (1, 20):
      words = units [digits] + ' ' + group + ' ' + words
    elif digits in range (20, 100):
      ten_digit, unit_digit = digits // 10, digits % 10
      words = tens [ten_digit] + ' ' + units [unit_digit] + ' ' + group + ' ' + words
    elif digits >= 100:
      words = number_to_words (digits) + ' crore ' + words

  return words