Numbers in written format

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Numbers in written format

Post by GeertDD »

I would like to convert (int) 1 to (string) "one", 2 to "two", 65 to "sixty-five", etc.

Does anybody know of a PHP function that does that? Some snippet maybe? Thanks.
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Re: Numbers in written format

Post by GeertDD »

Well, I quickly cooked something together myself. This works for numbers until 99. Does the job for my situation. Feel free to expand or improve the code.

Code: Select all

<?php
 
class text {
 
    /**
     * Converts a number (0-99) to its written version. Example: 5 becomes "five".
     * Larger or smaller numbers will be returned untouched.
     *
     * @param   integer
     * @return  string|integer
     */
    public static function num2str($num)
    {
        static $zero2nineteen = array
        (
            'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
            'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
        );
 
        static $twenty2ninety = array
        (
            2 => 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
        );
 
        // Done with invalid or out-of-range numbers
        if ( ! ctype_digit((string) $num) OR $num < 0 OR $num > 99)
            return $num;
 
        // 0-19 is hard-coded in the array
        if ($num < 20)
            return $zero2nineteen[$num];
 
        // Pull apart first and second digit
        $num = (string) $num;
        $str = $twenty2ninety[$num[0]];
        $str .= ($num[1] === '0') ? '' : '-'.$zero2nineteen[$num[1]];
 
        return $str;
    }
}
By the way, maybe somebody could move this to the code snippets forum? Thank you.
Post Reply