Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

php - convert large number to spoken english

Converting 'small' numbers to English is not to troublesome. But if you handle BCMath Arbitrary Precision numbers then it can be.

Using code from:

http://marc.info/?l=php-general&m=99928281523866&w=2

The maximum number seems to be:

two billion one hundred forty seven million four hundred eighty three thousand six hundred forty seven

Anyone know a function to convert numbers bigger than that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to write your own function, I suggest to use numbers as a string, let a substract like this:

    $string =  "12356";
    $text="";
    // level means 0-ones, 1- thousand , 2 million, 3 billion etc...
    $level=0;
    //until string has no character left
    while ($len=getval($string)){
      // get partial number from 0 to 999
      $string_partial = substr($string, (strlen($string)-$len)) ;
      // get hundreds
      $hund = ($string_partial - ($string_partial % 100))/100;
      // get tens
      $tens = $string_partial - ($hund *100);
      $tens = ($tens - ($tens %10))/10;
      // get ones
      $ones = $string_partial - ($tens*10) - ($hund*100);
      // remove partial_string form original string             
      $string = substr($string, 0, (strlen($string)-$len));
      // edbug echoing
      echo $level . " - " . $hund. " - " . $tens .  " - " . $ones . "<br>";
      // you need to create a function that convert number to text only from 0 to 999 to set correct million/thousand etc, use $level.
      //$text = getTextvalue($hund,$tens,$ones,$level).$text;
      //increment $level
      $level++;
    }
    function getval($n){
      switch (strlen($n)){
       case 0: return false;
       case 1: return 1;
       case 2: return 2;
       default: return 3;
       }
    }

example:

$string =  "123456789";

will output

 $level - $hund - $tens - $ones
 0 - 7 - 8 - 9  
 1 - 4 - 5 - 6  //thousand
 2 - 1 - 2 - 3  //million

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...