Home > php教程 > php手册 > body text

php实现将人民币金额转大写的办法

WBOY
Release: 2016-06-21 08:48:56
Original
1490 people have browsed it

工作中偶尔会碰到需要将人民币金额,也即阿拉伯数字转化为大写汉字的这种情况,下面是作者经过实践总结出来的方法,特此记录以防备忘。

class Num2Cny{
  static $basical=array(0=>'零','壹','贰','叁','肆','伍','陆','柒','捌','玖');
  static $advanced=array(1=>'拾','佰','仟');
  public static function ParseNumber($number){
    $number=trim($number);
    if(!is_numeric($number)intval($number)>999999999999) return 'error';
    if($number==0) return '零';
    if(strpos($number,'.')){
      $number=round($number,2);
      $data=explode('.',$number);
      $data[0]=self::int($data[0]);
      $data[1]=self::dec($data[1]);
      return $data[0].$data[1];
    }else{
      return self::int($number).'整';
    }
  }
  public static function int($number){
    $arr=array_reverse(str_split($number));
    $data='';
    $zero=false;
    $zero_num=0;
    foreach($arr as $k=>$v){
      $_chinese='';
      $zero=($v==0)?true:false;
      $x=$k%4;
      if($x && $zero && $zero_num>1)continue;
      switch($x){
        case 0:
          if($zero){
            $zero_num=0;
          }else{
            $_chinese=self::$basical[$v];
            $zero_num=1;
          }
          if($k==8){
            $_chinese.='亿';
          }elseif($k==4){
            $_chinese.='万';
          }
          break;  
        default:
          if($zero){
            if($zero_num==1){
              $_chinese=self::$basical[$v];
              $zero_num++;
            }
          }else{
            $_chinese=self::$basical[$v];
            $_chinese.=self::$advanced[$x];
          }
      }
      $data=$_chinese.$data;
    }
    return $data.'元';
  }
  public static function dec($number){
    if(strlen($number)$v){
      $zero=($v==0)?true:false;
      $_chinese='';
      if($k==0){
        if(!$zero){
          $_chinese=self::$basical[$v];
          $_chinese.='分';
          $zero_num=true;
        }
      }else{
        if($zero){
          if($zero_num){
            $_chinese=self::$basical[$v];
          }
        }else{
          $_chinese=self::$basical[$v];
          $_chinese.='角';
        }
      }
      $data=$_chinese.$data;
    }
    return $data;
  }
}
Copy after login

使用过程也很简单,如下:

echo Num2Cny::ParseNumber(1234567.5);//www.Alixixi.com
Copy after login

结果将输出:

壹佰贰拾叁万肆仟伍佰陆拾柒元伍角

另外说明一下的是如果仅需要将阿拉伯数字转化为大写的情况下,可参照本站文章:

PHP将阿拉伯数字转化为汉字的函数



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!