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

在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
相关推荐
千百元3 小时前
网络图标显示不正常
开发语言·网络·php
hans汉斯3 小时前
基于污点分析的PHP应用威胁检测平台
开发语言·人工智能·算法·yolo·目标检测·php·无人机
一次旅行3 小时前
Mac本地部署OpenClaw优化
开发语言·macos·php
博傅4 小时前
docker部署php项目
docker·eureka·php
luanma1509805 小时前
Laravel vs ThinkPHP:框架选择终极指南
php·laravel
ICT系统集成阿祥6 小时前
VLAN划分与端口隔离详解
开发语言·php
郑州光合科技余经理9 小时前
海外O2O系统源码剖析:多语言、多货币架构设计与二次开发实践
java·开发语言·前端·小程序·系统架构·uni-app·php
globaldomain15 小时前
什么是用于长距离高速传输的TCP窗口扩展?
开发语言·网络·php
桌面运维家17 小时前
Win10打印机共享故障排查:权限与网络配置详解
开发语言·网络·php
xht083219 小时前
PHP vs C语言:核心差异全解析
c语言·开发语言·php