Thread  RSS Function: numberToWords()



# 11535 9 years ago on Sat, Jan 16 2016 at 10:21 pm

Here's a handy PHP function I developed that converts numbers into their verbose, English-language equivalents:

function numberToWords($n){
  
  if($n < 1) return 'zero';
  if($n > 1000000000000) return $n; 

  // Just return the number if it's out of a reasonable range for this application.
  
  $n = intval($n); // We only deal with integers in this function.
  
  $o = '';
  
  $tens = Array('twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety');
  $ones = Array(
    'one',
    'two',
    'three',
    'four',
    'five',
    'six',
    'seven',
    'eight',
    'nine',
    'ten',
    'eleven',
    'twelve',
    'thirteen',
    'fourteen',
    'fifteen',
    'sixteen',
    'seventeen',
    'eighteen',
    'nineteen'
  );
  
  $units = Array(
    'trillion'  => 1000000000000,
    'billion'   => 1000000000,
    'million'   => 1000000,
    'thousand'  => 1000,
    'hundred'   => 100,
  );
  
  foreach($units as $unit => $amt){
    $x = floor($n / $amt);
    $n = $n - ($x * $amt);
    $o .= ($x > 0) ? numberToWords($x).' '.$unit.' ' : ' ';
  }
  
  if($n >=20){ // Process tens.
    $x = floor($n / 10);
    $n = $n - ($x * 10);
    $o .= ($x > 0) ? $tens[$x-2].' ' : ' ';
  }
  
  if($n > 0){ // Process ones.
    $o .= $ones[$n-1];
  }
  
  return trim($o);
  
}

The function is mostly for aesthetic and novelty purposes but if you can find a good use for it, please take advantage of it.

If you use it, please let me know; you certainly don't have to tell me but I'm interested in hearing from anyone who finds it useful!

73's, KD8FUD

User Image

# 11558 9 years ago on Sun, Jan 17 2016 at 12:43 am

This is clever! Actually, I really want to use this!

Wolfwood29 ports it to C#

Dude, post more functions like this. yay

"Dangerous toys are fun, but you could get hurt!"


Return to Index Return to topic list

Forgot password?
Currently Online
Users:0
Guests:23

Most Recently Online
ZOL3 weeks ago
Wolfwood293 weeks ago
lam3 weeks ago
Nitrocosm1 month ago
Jovian1 month ago