Home > 分享 > 将数字转换为大写人民币格式的函数

将数字转换为大写人民币格式的函数0+

13,773 views / 2010.06.02 / 2:02 下午

这个函数用来把数字转换为人民币大写格式,经过测试已经接近完美。如果有bug,欢迎反馈!

function toCNFormat($data) {
 $data = strpos($data, ".") === false? $data . ".00":$data;
 if (!preg_match("/^[0-9\.]+$/", $data))return "";
 $capnum = array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
 $capdigit = array("", "拾", "佰", "仟");
 $subdata = explode(".", $data);
 $yuan = $subdata[0];
 $j = 0;
 $nonzero = 0;
 for($i = 0;$i < strlen($subdata[0]);$i++) {
  if (0 == $i) {
   if ($subdata[1]) {
    $cncap = substr($subdata[0], -1, 1) != 0?"元":"元零";
   } else {
    $cncap = "元";
   }
  }
  if (4 == $i) {
   $j = 0;
   $nonzero = 0;
   $cncap = "万" . $cncap;
  }
  if (8 == $i) {
   $j = 0;
   $nonzero = 0;
   $cncap = "亿" . $cncap;
  }
  $numb = substr($yuan, -1, 1);
  $cncap = ($numb)?$capnum[$numb] . $capdigit[$j] . $cncap:(($nonzero)?"零" . $cncap:$cncap);
  $nonzero = ($numb)?1:$nonzero;
  $yuan = substr($yuan, 0, strlen($yuan)-1);
  $j++;
 }
 
 if ($subdata[1]) {
  $chiao = substr($subdata[1], 0, 1)?$capnum[substr($subdata[1], 0, 1)] . "角":"零";
  $cent = substr($subdata[1], 1, 1)?$capnum[substr($subdata[1], 1, 1)] . "分":"";
 }
 $cncap .= $chiao . $cent . "整";
 $cncap = preg_replace("/(零)+/", "\\1", $cncap);
 $cncap = str_replace("零整", "整", $cncap);
 return $cncap;
}
echo toCNFormat("110502.35");
本站内容受著作权法保护。个人 blog 转载时请遵循 “署名-非商业用途-保持一致” 的创作共用协议;商业网站或未授权媒体不得复制本站内容。
Categories: 分享 Tags: ,

Comments (0) Trackbacks (0) 本篇共有 0 篇评论↓
  1. No comments yet.
  1. No trackbacks yet.