Number to text conversion


Posted in: data | Save to del.icio.us | 25 Apr 2009



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 Responses

1

Shantanu Oak

May 13th, 2009 at 9:36 pm

>> One thing to note is that The billion/trillion etc suffixes are done using the American style

If you want British style, use Pear package called “Numbers Words”

http://pear.php.net/package/Numbers_Words

2

roy

September 2nd, 2009 at 8:29 pm

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 disabled for this post, but if you have spotted an error, feel free to contact me.

Get latest updates by E-mail

About this blog

This site is a digital habitat of Sameer, a freelance web developer working from Pune.More

  • Users Online

    • 6 Users Online
    • 6 Guests
  • RECENT COMMENTS

    ON TWITTER