如何修复我的Php函数,将数字转换为单词,输出11到19,而不是11?

时间:2019-02-19 09:20:45

标签: php currency

我在输出11到19的单词时遇到问题,而不是输出11而不是输出11和12输出10 2,依此类推,直到19,但是以十进制表示却正确地输出10到19。

最新的PHP,Web服务器

<?php
function toWords($num) {

  $ones = array(
    0 => "Zero",
    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",
    "014" => "Fourteen"
  );
  $tens = array(
    0 => "Zero",
    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"
  ); /*limit t 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, 1);
  $rettxt = "";
  foreach ($whole_arr as $key => $i) {

    while (substr($i, 0, 1) == "0")
      $i = substr($i, 1, 5);
    if ($i < 20) {
      /* echo "getting:".$i; */
      $rettxt .= $ones[$i];
    } elseif ($i < 100) {
      if (substr($i, 0, 1) != "0")  $rettxt .= $tens[substr($i, 0, 1)];
      if (substr($i, 1, 1) != "0") $rettxt .= " ".$ones[substr($i, 1, 1)];
    } else {
      if (substr($i, 0, 1) != "0") $rettxt .= $ones[substr($i, 0, 1)]." ".$hundreds[0];
      if (substr($i, 1, 1) != "0")$rettxt .= " ".$tens[substr($i, 1, 1)];
      if (substr($i, 2, 1) != "0")$rettxt .= " ".$ones[substr($i, 2, 1)];
    }
    if ($key > 0) {
      $rettxt .= " ".$hundreds[$key]." ";
    }
  } $rettxt = $rettxt." Pesos";
  if ($decnum > 0) {
    $rettxt .= " and ";
    if ($decnum < 20) {
      $rettxt .= $ones[$decnum];
    } elseif ($decnum < 100) {
      $rettxt .= $tens[substr($decnum, 0, 1)];
      $rettxt .= " ".$ones[substr($decnum, 1, 1)];
    }

    $rettxt = $rettxt." Centavos";
  }
  return $rettxt;
}
?>

输出是十二而不是十二(十一到十九) 但是以十进制形式可以正确输出单词 十一点到十九点

四十二万十二比索(P 4,212.00), 一千九百个十个比索和十八个圣塔沃斯(P 1,917.18)... 我在以下网站上找到了此代码:https://www.studentstutorial.com/php/number-to-words.php

1 个答案:

答案 0 :(得分:0)

<?php

$number = '11545';
$locale = 'en_US';
$format = numfmt_create($locale, NumberFormatter::SPELLOUT);
$in_words = numfmt_format($format, $number);

print_r($in_words);
// eleven thousand five hundred forty-five

?>