Number Speller

Here is a PHP function that takes a number and spells it out in English:


<?php
/**
* English number speller (PHP 4 or greater)
*
* @param string $number a string representing a positive, integral number with 15 digits or less
* @return string|false the spelled out number in English, or false if the number is invalid
* @author {@link http://www.lesantoso.com Lucky E. Santoso} <lesantoso@yahoo.com>
* @copyright Copyright (c) 2006 Lucky E. Santoso
* @license http://opensource.org/licenses/gpl-license.php The GNU General Public License (GPL)
*/  
function spellNumberInEnglish ($number) {
	$number = strval($number);
	if (!ereg("^[0-9]{1,15}$", $number)) 
		return(false); 
	$ones = array("", "one", "two", "three", "four", 
		"five", "six", "seven", "eight", "nine");
	$teens = array("ten", "eleven", "twelve", "thirteen", "fourteen", 
		"fifteen", "sixteen", "seventeen", "eighteen", "nineteen");
	$tens = array("", "", "twenty", "thirty", "forty", 
		"fifty", "sixty", "seventy", "eighty", "ninety");
	$majorUnits = array("", "thousand", "million", "billion", "trillion");
	$result = "";
	$isAnyMajorUnit = false;
	$length = strlen($number);
	for ($i = 0, $pos = $length - 1; $i < $length; $i++, $pos--) {
		if ($number{$i} != '0') {
			if ($pos % 3 == 0)
				$result .= $ones[$number{$i}] . ' ';
			else if ($pos % 3 == 1) {
				if ($number{$i} == '1') {
					$result .= $teens[$number{$i + 1}] . ' ';
					$i++; $pos--;
				} else {
					$result .= $tens[$number{$i}];
					$result .= $number{$i + 1} == '0'? ' ' : '-';
				}
			} else 
				$result .= $ones[$number{$i}] . " hundred ";
			$isAnyMajorUnit = true;
		}
		if ($pos % 3 == 0 && $isAnyMajorUnit) {
			$result .= $majorUnits[$pos / 3] . ' ';
			$isAnyMajorUnit = false;
		}
	}
	$result = trim($result);
	if ($result == "") $result = "zero";
	return($result);
}
?>

See also: Indonesian Numbers (this function in action)

2 Comments to “Number Speller”

  1. Anonymous Says:

    Many many thx 4 the script

  2. mahesh Says:

    it very good number to word conversion function

Leave a Comment

Security Code: