数字转人民币金额大写

php

浏览数:315

2019-1-7


numToRmb.php

<?php
header("content-type:text/html;charset=utf-8");
function numToRmb($num){
  $rmbNum = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖'];
  $rmbUnit = ['分','角','元','拾','佰','仟','万','拾','佰','仟','亿','拾','佰','仟','万','拾','佰','仟'];
  //数字预处理
  if($num == '' || $num == 0){
    return '请输入一个大于0的金额,谢谢!';
  }else {
    $num = number_format($num, 2, '.', '')*100;
  }
  if (strlen(number_format($num, 0, '', ''))>18) {
    return '输入的金额不得超过千万亿!';
  }
  //开始数字转换人民币大写
  $out1 = 0;
  $numRmb = '';
  $unit = '';
  $rmb = '';
  for ($out1 = 0 ; $out1 < strlen(number_format($num, 0, '', '')) ; $out1++) {
    $numRmb = $rmbNum[substr(number_format($num, 0, '', ''), $out1, 1)];
    $unit = $rmbUnit[strlen(number_format($num, 0, '', ''))-$out1-1];
    $rmb = $rmb.$numRmb.$unit;
  }
  // 将大写人民币中的零进行调整
  $rmbStrlen = strlen($rmb);
  for ($out2=0; $out2 < $rmbStrlen; $out2=$out2+3) {
    $tempRmb = substr($rmb, $out2, 6);
    if ($tempRmb=='零元'||$tempRmb=='零万'||$tempRmb=='零亿') {
      $left = substr($rmb, 0, $out2);
      $right = substr($rmb, $out2+3);
      $rmb = $left.$right;
      $out2 = $out2 - 3;
      $rmbStrlen = $rmbStrlen - 3;
    }elseif ($tempRmb=='零拾'||$tempRmb=='零佰'||$tempRmb=='零仟') {
      $left = substr($rmb, 0, $out2+3);
      $right = substr($rmb, $out2+6);
      $rmb = $left.$right;
      $out2 = $out2 - 3;
      $rmbStrlen = $rmbStrlen - 3;
    }elseif ($tempRmb=='零分'||$tempRmb=='零角') {
      $left = substr($rmb, 0, $out2);
      $right = substr($rmb, $out2+6);
      $rmb = $left.$right;
      $out2 = $out2 - 6;
      $rmbStrlen = $rmbStrlen - 6;
    }
    if ($tempRmb=='零零') {
      $left = substr($rmb, 0, $out2);
      $right = substr($rmb, $out2+3);
      $rmb = $left.$right;
      $out2 = $out2 - 3;
      $rmbStrlen = $rmbStrlen - 3;
    }
    if(substr($rmb,strlen($rmb)-3)=='元') {
      $rmb = $rmb.'整';
    }
  }
  return $rmb;
}
echo numToRmb($_POST['num']);
 ?>