Number to text conversion

phpguru.org offers a small and useful class to convert numbers to their textual equivalent. If you are building a accounting or invoicing application it may come in handy. The class can be downloaded form here. A sample code using the class is shown below.

<?php
 
    require_once 'libs/numtotext.php';
 
 
    $tt = new TextualNumber();
 
    /* Catch 'out of range' and 'invalid character' exceptions */
    try {
        echo $tt->GetText("197533408989");
    }
    catch(Exception $e) {
        echo $e->getMessage();
    }
 
?>

The above code prints:

one hundred and ninety-seven billion 
five hundred and thirty-three million 
four hundred and eight thousand 
nine hundred and eighty-nine

The class supports a range up to 999999999999999999 and also supports decimal numbers.
One thing to note is that The billion/trillion etc suffixes are done using the American style (eg 9 zeros for billion, 12 for trillion).

2 thoughts on “Number to text conversion

  1. nice, thanx, but i suggest that would better if you delete the “and ” in hundred

    // Three digit number
    case ‘3’:
    if ($int % 100 == 0) {
    $text = self::$units[$int{0}] . ‘ hundred’;
    } else {
    $text = self::$units[$int{0}] . ‘ hundred and ‘ . self::GetText(substr($int, 1));
    }
    break;

    example:

    197533408989.89

    result:

    One hundred ninety-seven billion,
    five hundred thirty-three million,
    four hundred eight thousand,
    nine hundred eighty-nine and 89/100

Comments are closed.