Created
March 6, 2013 20:02
-
-
Save andrewwheal/5102562 to your computer and use it in GitHub Desktop.
Function to convert a number to text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static function convertNumToString($number, $limit = 999999999999) { | |
if (($number < 0) || ($number > $limit)) { | |
return $number; | |
} | |
if ($number == 0) { | |
return "zero"; | |
} | |
$Tn = floor($number / 1000000000); /* Trillions (tera) */ | |
$number -= $Tn * 1000000000; | |
$Gn = floor($number / 1000000); /* Millions (giga) */ | |
$number -= $Gn * 1000000; | |
$kn = floor($number / 1000); /* Thousands (kilo) */ | |
$number -= $kn * 1000; | |
$Hn = floor($number / 100); /* Hundreds (hecto) */ | |
$number -= $Hn * 100; | |
$Dn = floor($number / 10); /* Tens (deca) */ | |
$n = $number % 10; /* Ones */ | |
$string = ""; | |
if ($Tn) { | |
$string .= self::convertNumToString($Tn) .' Trillion'; | |
} | |
if ($Gn) { | |
$string .= self::convertNumToString($Gn) .' Million'; | |
} | |
if ($kn) { | |
$string .= ( empty($string) ?'' :' ') . | |
self::convertNumToString($kn) .' Thousand'; | |
} | |
if ($Hn) { | |
$string .= ( empty($string) ?'' :' ') . | |
self::convertNumToString($Hn) .' Hundred'; | |
} | |
$ones = array('','One','Two','Three','Four','Five','Six', | |
'Seven','Eight','Nine','Ten','Eleven','Twelve','Thirteen', | |
'Fourteen','Fifteen','Sixteen','Seventeen','Eighteen', | |
'Nineteen'); | |
$tens = array('','','Twenty','Thirty','Forty','Fifty','Sixty', | |
'Seventy','Eighty','Ninety'); | |
if ($Dn || $n) { | |
if (!empty($string)) { | |
$string .=' and '; | |
} | |
if ($Dn < 2) { | |
$string .= $ones[$Dn * 10 + $n]; | |
} else { | |
$string .= $tens[$Dn]; | |
if ($n) { | |
$string .= ' ' . $ones[$n]; | |
} | |
} | |
} | |
return $string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment