Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a number to its string representation

Tags:

string

php

I'm developing a simple web application where in I need to display number a to my users in string format.

Example:

12 - One Two or Twelve
-20 - minus Two zero or minus twenty

Either way is fine. I need this to be done in PHP. Any help will be appreciated.

like image 944
Webdev Avatar asked Dec 18 '22 02:12

Webdev


2 Answers

for the first option (spell out digits), strtr is your friend

$words = array(
  '-' => 'minus ',
  '1'  => 'one ',
  '2' => 'two ',
etc....
);

echo strtr(-123, $words);
like image 128
user187291 Avatar answered Dec 29 '22 19:12

user187291


If you want to spell out the complete number you can make use of the PEAR Numbers_Words class. This class has a toWords() method that accepts a +ve or a -ve num and returns the spelled out string representation of the number.

If you want to convert the number to string digit wise, I am not aware of any lib function. But you can code one yourself easily. user187291 gives a good way to do this in his answer.

<?php

$arr = array(
        -12,
        20
            );

foreach($arr as $num) {
        $nw = new Numbers_Words();
    echo "$num = ". $nw->toWords($num)."\n";
}    

?>

Output:

C:\>php a.php
-12 = minus twelve
20 = twenty
like image 36
codaddict Avatar answered Dec 29 '22 17:12

codaddict