使用NumberFormatter类在php中的单词数

时间:2017-10-03 03:26:55

标签: php numbers words

我难以在php中解决我的数字到单词功能。



<?php

  $num = 29.29;
  $f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
  echo $f->format($num);
  //outputs Twenty-nine and two nine
?>
&#13;
&#13;
&#13;

如何将其格式化为: 二十九和二十九?

请帮忙!

2 个答案:

答案 0 :(得分:4)

首先,29.29的发音应该是Twenty nine point two nine。话虽如此,如果您需要准确Twenty-nine and Twenty-nine,可以使用以下内容:

<?php
  $num = 29.29;
  $exp = explode('.', $num);
  $f = new NumberFormatter("en_US", NumberFormatter::SPELLOUT);
  echo ucfirst($f->format($exp[0])) . ' and ' . ucfirst($f->format($exp[1]));
  //outputs Twenty-nine and Twenty-nine
?>

答案 1 :(得分:0)

function numberTowords($num)
{ 
  $ones = array(        
    1 => "one", 
    2 => "two", 
    3 => "three", 
    4 => "four", 
    5 => "five", 
    6 => "six", 
    7 => "seven", 
    8 => "eight", 
    9 => "nine", 
    10 => "ten", 
    11 => "eleven", 
    12 => "twelve", 
    13 => "thirteen", 
    14 => "fourteen", 
    15 => "fifteen", 
    16 => "sixteen", 
    17 => "seventeen", 
    18 => "eighteen", 
    19 => "nineteen" 
    ); 
    $tens = array( 
    1 => "ten",
    2 => "twenty", 
    3 => "thirty", 
    4 => "forty", 
    5 => "fifty", 
    6 => "sixty", 
    7 => "seventy", 
    8 => "eighty", 
    9 => "ninety" 
); 

$hundreds = array( 
    "hundred", 
    "thousand", 
    "million", 
    "billion", 
    "trillion", 
    "quadrillion" 
);  

$num = number_format($num,2,".",","); 
$num_arr = explode(".",$num); 
$wholenum = $num_arr[0]; 
$decnum = $num_arr[1]; 
$whole_arr = array_reverse(explode(",",$wholenum)); 
krsort($whole_arr); 
$rettxt = ""; 

foreach($whole_arr as $key => $i){ 

    if($i < 20){ 
        $rettxt .= $ones[$i]; 
    }elseif($i < 100){ 
        $rettxt .= $tens[substr($i,0,1)]; 
        @$rettxt .= " ".$ones[substr($i,1,1)]; 
    }else{ 
        $rettxt .= $ones[substr($i,0,1)]." ".$hundreds[0]; 
        $rettxt .= " ".$tens[substr($i,1,1)]; 
        $rettxt .= " ".$ones[substr($i,2,1)]; 
    } 
    if($key > 0){ 
        $rettxt .= " ".$hundreds[$key]." "; 
    } 
} 
if($decnum > 0){ 
    $rettxt .= " and "; 
if($decnum < 20){ 
    $rettxt .= $ones[intval( $decnum) ]; 
}elseif( $decnum < 100){ 
    $rettxt .= $tens[substr($decnum,0,1)]; 
    $rettxt .= " ".$ones[substr($decnum,1,1)]; 
} 
 } 
 return $rettxt; 
} 

echo numberTowords( 29.29 );

https://www.phptpoint.com/convert-number-into-words-in-php/