人民币数字和中文汉字转换

在PHP中,将人民币的中文汉字金额转换为数字,或者将数字转换为人民币的中文汉字金额,通常需要自定义一些函数来实现这一转换过程。下面分别给出这两个转换的示例代码。

数字转人民币中文汉字

php 复制代码
function numberToChinese($num) {  
    $cnNums = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');  
    $cnUnits = array('', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿');  
    $numStr = strval($num);  
    $numStr = array_reverse(str_split($numStr));  
    $result = '';  
    $zeroCount = 0;  
      
    for ($i = 0; $i < count($numStr); $i++) {  
        $digit = intval($numStr[$i]);  
        $unit = $cnUnits[$i % 4];  
          
        if ($digit === 0) {  
            $zeroCount++;  
        } else {  
            if ($zeroCount > 0) {  
                $result = $cnNums[0] . $result;  
            }  
            $zeroCount = 0;  
            $result = $cnNums[$digit] . $unit . $result;  
        }  
          
        if (($i + 1) % 4 === 0 && $digit !== 0) {  
            $result = $cnUnits[4 + intval(($i + 1) / 4) - 1] . $result;  
        }  
    }  
      
    $result = trim($result, $cnNums[0]); // 去除结果字符串两边的零  
    if (empty($result)) {  
        $result = $cnNums[0]; // 如果结果为空,则返回零  
    }  
      
    return '人民币' . $result . '元整';  
}  
  
// 示例用法  
echo numberToChinese(123456789); // 输出:人民币壹亿贰仟叁佰肆拾伍万陆仟柒佰捌拾玖元整

人民币中文汉字转数字

php 复制代码
function chineseToNumber($chinese) {  
    // 去除人民币和元整等字样  
    $chinese = preg_replace('/人民币|元整|元正|元|整|正/i', '', $chinese);  
    $cnNums = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');  
    $cnUnits = array('', '拾', '佰', '仟');  
    $unitPosition = array(1, 10, 100, 1000); // 个、十、百、千  
    $num = 0;  
    $position = 0; // 万位、亿位等的位置,初始为个位  
    $isPrevZero = false; // 前一个数字是否为零  
  
    $chinese = str_split($chinese);  
    for ($i = 0; $i < count($chinese); $i++) {  
        $char = $chinese[$i];  
        if (in_array($char, $cnNums)) {  
            $digit = array_search($char, $cnNums);  
            if ($digit === 0 && $isPrevZero) {  
                continue; // 连续的零只计算一个  
            }  
            $num += $digit * $unitPosition[$i % 4] * pow(10000, intval($position));  
            $isPrevZero = ($digit === 0);  
        } elseif (in_array($char, $cnUnits)) {  
            if ($char === '万' || $char === '亿') {  
                $position++;  
            }  
        }  
    }  
  
    return $num;  
}  
  
// 示例用法  
echo chineseToNumber('人民币壹亿贰仟叁佰肆拾伍万陆仟柒佰捌拾玖元整'); // 输出:123456789
相关推荐
小鹿( ﹡ˆoˆ﹡ )26 分钟前
探索IP协议的神秘面纱:Python中的网络通信
python·tcp/ip·php
XKSYA(小巢校长)2 小时前
NatGo我的世界联机篇
开发语言·php
lxp1997413 小时前
php函数积累
开发语言·php
ac-er88885 小时前
PHP“===”的意义
开发语言·php
wxin_VXbishe5 小时前
springboot合肥师范学院实习实训管理系统-计算机毕业设计源码31290
java·spring boot·python·spring·servlet·django·php
小小不董5 小时前
《Linux从小白到高手》理论篇:深入理解Linux的网络管理
linux·运维·服务器·数据库·php·dba
豆豆6 小时前
为什么用PageAdmin CMS建设网站?
服务器·开发语言·前端·php·软件构建
NiNg_1_2347 小时前
ThinkPHP5基础入门
php
2401_857610038 小时前
SpringBoot实现:校园资料分享平台开发指南
服务器·spring boot·php
Q_w77428 小时前
一个真实可用的登录界面!
javascript·mysql·php·html5·网站登录