Created
July 8, 2013 17:05
-
-
Save pietvanzoen/5950599 to your computer and use it in GitHub Desktop.
Numbers to words :: A php library for converting numbers to words. Useful for bio copy that includes years since an event. Also useful for dynamically rendering grid systems that use words such as class="columns six". #php
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
<?php | |
// Goes in codeigniter/libraries | |
if (!defined('BASEPATH')) | |
exit('No direct script access allowed'); | |
class Numbertowords { | |
function convert_number($number) { | |
if (($number < 0) || ($number > 999999999)) { | |
throw new Exception("Number is out of range"); | |
} | |
$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 */ | |
$res = ""; | |
if ($Gn) { | |
$res .= $this->convert_number($Gn) . "million"; | |
} | |
if ($kn) { | |
$res .= (empty($res) ? "" : " ") .$this->convert_number($kn) . " thousand"; | |
} | |
if ($Hn) { | |
$res .= (empty($res) ? "" : " ") .$this->convert_number($Hn) . " hundred"; | |
} | |
$ones = array("", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eightteen", "nineteen"); | |
$tens = array("", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eigthy", "ninety"); | |
if ($Dn || $n) { | |
if (!empty($res)) { | |
$res .= " and "; | |
} | |
if ($Dn < 2) { | |
$res .= $ones[$Dn * 10 + $n]; | |
} else { | |
$res .= $tens[$Dn]; | |
if ($n) { | |
$res .= "-" . $ones[$n]; | |
} | |
} | |
} | |
if (empty($res)) { | |
$res = "zero"; | |
} | |
return $res; | |
} | |
} | |
?> |
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
<?php | |
// Codeigniter helper function for numbers to words library | |
function numberstowords($number) | |
{ | |
$CI =& get_instance(); | |
$CI->load->library('numbertowords'); | |
return $CI->numbertowords->convert_number($number); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment