Home  >  Article  >  Backend Development  >  How to convert php numbers to Chinese characters

How to convert php numbers to Chinese characters

PHPz
PHPzOriginal
2023-04-18 09:47:261667browse

When developing a digital system, converting numbers into Chinese characters is an unavoidable need. For example, in the financial system, converting numerical amounts into uppercase Chinese characters can conveniently and clearly express the amount. As a popular web development language, PHP's built-in function libraries and extensions allow it to cope with this demand.

This article will introduce readers to the implementation of converting numerical values ​​into Chinese characters, including some common algorithms and function libraries. I hope it can help developers realize the function of converting numbers into Chinese characters in their own projects.

1. Basic Numeric Conversion Chinese Character Algorithm

The most basic method is to divide the numbers in groups of four in order from the left side of the number, and the maximum unit of grouping is ten thousand or billion levels . The numerical values ​​in each group are converted into corresponding Chinese character expressions through an algorithm, and then the Chinese characters of these numbers can be spliced ​​together. Therefore, we first need to define the relationship between numbers and Chinese characters:

Numbers 0~9: zero, one, two, three, four, five, six, seven, eight, nine
Numbers 10~19 : Ten, eleven, twelve,..., eighteen, nineteen
Number 20~90 (step size is 10): Twenty, thirty,..., eighty, ninety
Number 100 : One hundred
Number 1000: One thousand
Number 10000: Ten thousand
Number 100000000: One hundred million

Then, group the values ​​you want to convert (the maximum unit can be adjusted as needed) , the values ​​in each group are converted according to the following rules:

  1. If the number is 0, directly output "zero"
  2. If the number is greater than or equal to 10, but less than 20, follow Output in the format of "tens" (such as "eleven", "twelve"..."nineteen")
  3. If the number is greater than or equal to 20, it is converted into the format output of "tens" (such as "two" "Ten", "Thirty"..."Ninety")
  4. If the number is greater than or equal to 100, convert it to the format of "X hundred" and output it, and recursively process values ​​below the hundredth place
  5. If the number is greater than or equal to 1000, convert it to the format of "X thousand" and output it, and recursively process the values ​​below the thousandth place
  6. If the number is greater than or equal to 10000, convert it to the format of "X thousand" and output it, and The last four digits are recursively processed
  7. If the number is greater than or equal to 100000000, it is converted into the format of "X billion" and output, and the last eight digits are recursively processed

The algorithm is as follows:

function num2chn($num) {

$chnnum = '';
$unit = array('','十','百','千','万','十','百','千','亿','十','百','千','兆');
$datacn = array('零','一','二','三','四','五','六','七','八','九');
$sign = $num < 0 ? &#39;负&#39; : &#39;&#39;;
$num = abs($num);
$numstr = strval($num);      
$alen = strlen($numstr);
$pos = $alen - 1;
$lastunit = true;
for ($i = 0; $i < $alen; $i++) {
    $curidx = intval($numstr[$i]);
    $curunit = $unit[$pos];
    if ($curidx > 0) {
        $chnnum .= $datacn[$curidx] . $curunit;
        $lastunit = true;
    } 
    else if (!$lastunit) {
        $chnnum .= $datacn[$curidx];
        $lastunit = true;
    }
    if ($pos == 4 && ($lastunit || $curidx)) {
        $chnnum .= '万';
    } 
    else if ($pos == 8 && ($lastunit || $curidx)) {
        $chnnum .= '亿';
    }
    $pos--;
}
if (!$chnnum) {
    $chnnum .= '零';
}
$chnnum = $sign . $chnnum;
return $chnnum;

}

This algorithm adopts the idea of ​​grouping and step-by-step conversion, processing each bit in sequence according to the number of digits in the value, and converting the number Expressed in Chinese characters. It should be noted that the handling of zeros requires special processing, and the output is ensured at the end.

2. Conversion between other numerical values ​​and Chinese characters

In PHP, you may also need to convert numerical values ​​​​such as amounts into standardized Chinese character expressions, such as "Ten thousand three hundred and two" Ten Yuan", or convert the Chinese amount into a numerical representation. Here we introduce a relatively complete conversion scheme between numerical values ​​and Chinese characters.

(1) Convert numerical value to Chinese character expression

This algorithm converts numerical value into Chinese character expression through loop recursion, which can be used to express the amount in Chinese capital letters. It divides the value into an integer part and a decimal part. The integer part adopts a logic similar to that in the basic algorithm, and the decimal part is converted from left to right for each digit.

function numtochn($num) {

$chncharacters = array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
$chnunits = array("", "拾", "佰", "仟", "万", "亿");
$level = array("", "万", "亿");
list($numInteger, $numDecimal) = explode(".", $num);
$integerStr = strrev($numInteger);   
$len = strlen($integerStr);        
$dwNum = 0;                         
$numAnsStr = sprintf("%s整", $level[0]); 

for ($i = 0;$i < $len; $i++) {     
    $tmpStr = &#39;&#39;;
    $perChar = substr($integerStr, $i, 1);
    $perInt = intval($perChar);
    if ($perInt == 0) {
        if ($i % 4 == 0) {
            $dwNum ++;
        }
        if ($dwNum > 0 && $dwNum % 2 == 0) {
            $tmpStr = $level[$dwNum / 2];
        }
        if ($i == $len - 1 || $i % 4 == 3) {
            $tmpStr .= $chnunits[4 + (($i + 1) % 4)];
            $dwNum = 0;
        }
        $numAnsStr = $tmpStr . $numAnsStr;
        continue;
    }
    $tmpStr = $chncharacters[$perInt];
    $tmpStr .= $chnunits[$i % 4]; 
    if ($i % 4 == 3) {
        $tmpStr .= $level[$dwNum / 2];
        $dwNum = 0;
    }
    $numAnsStr = $tmpStr . $numAnsStr;  
}

$numAnsStr = str_replace("零拾", "零", $numAnsStr);        
$numAnsStr = str_replace("零佰", "零", $numAnsStr);         
$numAnsStr = str_replace("零仟", "零", $numAnsStr);     
$numAnsStr = str_replace("零万", "万", $numAnsStr); 
$numAnsStr = str_replace("零亿", "亿", $numAnsStr);         
while (strpos($numAnsStr, "零零") !== false) {
    $numAnsStr = str_replace("零零", "零", $numAnsStr);
}
$numAnsStr = str_replace("亿万", "亿", $numAnsStr);        
if ($numDecimal != '') {  
    $decimalStr = '';
    for ($i = 0; $i < strlen($numDecimal); $i++) {
        $decimalStr .= $chncharacters[intval(substr($numDecimal, $i, 1))].$chnunits[$i+1];
    }
    $numAnsStr .= str_replace("零零", "零", $decimalStr);
}
return $numAnsStr;

}

(2) Convert Chinese character expression to numerical value

You can use regular expressions to realize the amount of Chinese characters Conversion, convert Chinese characters into corresponding numbers bit by bit, and accumulate them. If "10,000" or "100 million" is encountered, the accumulated result will be multiplied by the corresponding carry factor.

function chntoNum($str) {

$dict = array(&#39;零&#39;=>0,'壹'=>1,'贰'=>2,'叁'=>3,'肆'=>4,'伍'=>5,'陆'=>6,'柒'=>7,'捌'=>8,'玖'=>9,'一'=>1,'二'=>2,'三'=>3,'四'=>4,'五'=>5,'六'=>6,'七'=>7,'八'=>8,'九'=>9,'十'=>10,'百'=>100,'千'=>1000,'万'=>10000,'亿'=>100000000,'元'=>1,'角'=>0.1,'分'=>0.01);
preg_match_all("/[一二三四五六七八九十百千万亿角分]/u", $str, $match);
$match = $match[0];
$result=0;
$temp=1;
foreach($match as $value){
    $num=$dict[$value];
    if($num==100000000||$num==10000){
        $result+=$temp*$num;
        $temp=1;
    }else if($num>=10&&$num<100){
        $temp*= $num;
    }else if($num<10){
        $temp*= 10;
        $result +=$temp*$num;
        $temp = 1;
    }
}
if($temp!=1){
    $result += $temp;
}
return sprintf("%.2f", $result);

}

In this way, we can easily implement the combination of numbers and Chinese characters in our own projects by calling these functions. conversion between.

The above is the detailed content of How to convert php numbers to Chinese characters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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