...

View Full Version : Getting a string from a number format (eg changing 2 into two)



kjc
04-12-2003, 03:00 PM
Does anyone know if it is possible to do this? Ie to change 3 into three and 11 into eleven etc...

missing-score
04-12-2003, 07:37 PM
As far as I know, there is no function for this.

A long way round, but you could use an array of names...




$nums = array('one','two','three','four','five','six','seven','eight','nine');

$num = 3;

$num = str_replace($num,$nums[($num-1)],$num);



That should work. depends on how many numbers you wanna compensate for :rolleyes:

x_goose_x
04-12-2003, 08:47 PM
A correction has been made.


Note: the $break3 array can be extended as high as you would like.

missing-score
04-12-2003, 10:55 PM
WOW! Cool Function!

x_goose_x
04-13-2003, 03:34 PM
Fixed a bug. It wasmessing up when converting the tens and ones, when below 20.



<?php

function num2words ($num) {
$num = ereg_replace("[^0-9]", "", $num); //removes all non-numeric characters.
$break3 = Array ("","Thousand","Million","Billion","Trillion","Quadrillion","Quintillion");
$one2twenty = Array ("","One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
$tens = Array("","","Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety");
$num_split = Array();
while ( strlen($num) > 0 ) {
if ( strlen($num) > 3 ) {
$num_split[] = substr($num, (strlen($num)-3));
$num = substr($num, 0, (strlen($num)-3));
} else {
$num_split[] = $num;
$num = "";
}
}
$num_split = array_reverse ($num_split);
$ret = "";
foreach ( $num_split as $key=>$val ) {
$suff = sizeof($num_split)-$key-1;
if ( $val < 20) {
$val = $one2twenty[$val];
} else {
if ( $val >= 100 ) {
$hun = $one2twenty[$val{0}]." Hundred";
$ten = $val{1};
$one = $val{2};
} else {
$ten = $val{0};
$one = $val{1};
}
if ( $ten >= 2 ) {
$val = $tens[$ten]."-".$one2twenty[$one];
} else {
$val = $one2twenty[$ten.$one];
}
}
$ret .= "$hun $val $break3[$suff]";
if ( $suff != "" ) $ret .= ", ";
}
return $ret;
}

print num2words($_GET['num']);

?>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum