search

Home  >  Q&A  >  body text

php - Interview question, convert numbers within 100 into Chinese...

How to quickly convert numbers into text
For example, 1 => one, 2=> two, ..., 15=》Fifteen
What I am currently thinking about is to save Chinese characters into a In array

$arr = ['一','二','三','四','五','六','七','八','九','十'];

But this is too troublesome. How to convert the input numbers into Chinese? Is there an easier way?

The final result is as follows:
Input 12
Output

 一二三四五六七八九十十一十二
PHP中文网PHP中文网2752 days ago1010

reply all(6)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-06-14 10:52:09

    <?php
            $number=57;
            $arr=array(
    
                    '1'    =>    '一',
                    '2'    =>    '二',
                    '3'    =>    '三',
                    '4'    =>    '四',
                    '5'    =>    '五',
                    '6'    =>    '六',
                    '7'    =>    '七',
                    '8'    =>    '八',
                    '9'    =>    '九',
                    '10'    =>    '十',
    
                );
            if($number>10){
                //倍数
                $bs    =    (int)($number/10);
                //余数
                $ys    =    $number%10;
                echo $arr[$bs].$arr[10].$arr[$ys];
    
            }else{
                echo $arr[$number];
    
            }
    
        

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-14 10:52:09

    If you can describe the digital conversion process clearly in words, then writing code is a process of translation.

    The algorithm is actually just business logic with very strange business logic. The focus is on analyzing this business logic

    You can convert Arabic numerals to Chinese numerals even before you graduate from elementary school. You must have a method in your mind to complete this conversion process. So the focus of the investigation here is the abstractionprocess of the problem. To be abstract and accurate, you must first have a comprehensive analysis and understanding of the problem itself and find out the rules. In the process of digital conversion, when is 0 called ten and when is it called zero. This process is so natural in the mind that it still requires a certain amount of ability to analyze its situation and find out the rules.

    I recommend this article. The analysis at the beginning of the article is the abstraction process, which is very important for programming

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-14 10:52:09

    $setnumber = 99;
            $chiNum = array('十','一','二','三','四','五','六','七','八','九','十');
            if($setnumber < 100 && $setnumber >= 1) {
                for($i = 1;$i<=$setnumber;$i++) {
                    $setstrnumber = (string)$i;
                    $count = strlen($setstrnumber);
                    if($count == 1) {
                        echo $chiNum[$i]."<br/>"; 
                    } else {
                        $setchinum = '';
                        if($setstrnumber[0] != 1) {                      
                            $setchinum .= $chiNum[$setstrnumber[0]];
                        }
                        $setchinum .= $chiNum[0];
                        
                        if(intval($setstrnumber[1]) != 0) {
                            $setchinum .= $chiNum[$setstrnumber[1]];
                        }
                        echo $setchinum."<br/>";
                    }
                }
            }

    reply
    0
  • PHP中文网

    PHP中文网2017-06-14 10:52:09

    How to quickly convert numbers into text
    For example, 1 => one, 2=> two, ..., 15=》Fifteen
    What I am currently thinking about is to save Chinese characters into an array

    $arr = ['一','二','三','四','五','六','七','八','九','十'];

    But this is too troublesome. How to convert the input numbers into Chinese? Is there an easier way?

    The final result is as follows:
    Input 12
    Output

    一二三四五六七八九十十一十二

    The following is the implementation of JavaScript

    Observe the numerical representation of Chinese characters

    Chinese characters explicitly specify the order of numbers. For example, One hundred and one contains the order of hundreds (one hundred and ten million)

    2 >>>> Two
    10 >>>> Ten 16 >>>>

    Ten

    Six >>>> Sixteen 105 >>>>

    One hundred

    Zero ten Five >>>> One hundred and five 1024 >>

    You can see that its representation can be seen as the form of

    value + order. In addition, when the following conditions are met, need to omit the order or value 10 corresponds to one ten writing

    ten

    110

    corresponds to

    one hundred and ten writing one hundred and ten

    ....and so on

    Based on the above thinking, the programming idea that should be drawn is as follows: Enter numbers
    n Map n
    to an array

    tokens
    . For example,

    8

    becomes
      ["eight"]
    1. ,

      101 becomes ["one", "zero", "one"]

    2. Add level 101 becomes ["一", "百", "十", "zero", "一", "一"] Filter, for example, One hundred and one becomes the simplest form One hundred and one

    3. Tool function

      // 数字到汉字的映射表 
      var mapHans = ['零', '一','二','三','四','五','六','七','八','九','十'];
      
      // 用 n 得到汉字 输入 0 得到 '零'
      var getHans = n => mapHans[n]; 
      
      // 数字长度到汉字数级的映射表 
      var mul = ['十', '百', '千', '万']
      
      // ['i', 'love', 'my', 'wife'] >>>> ilovemywife 
      var arr2str = arr => arr.join(''); 
      
      // 输入 5 产生 [1, 2, 3, 4, 5]
      var arrGenerator = n => (
          new Array(n).fill(0).map((e, idx) => idx + 1)
      )
      Achieved

      First implement the mapping of
    4. numbers
    5. greater than 10

      to the number system of Chinese characters For example, enter 101

      and return
    6. One hundred and one

    It will be faster to use the tool function written above

    var toHans = n => {
        // 比如输入 101 返回 ['一', '零', '一']
        var tokens = n.toString().split('').map(getHans); 
        
        // 对数阶的处理  如果上一步得到 ['一', '零', '一'] 
        // 那么at就是 ['百', '十']
        var at = mul.slice(0, tokens.length - 1).reverse();   
        
        // 归约 
        return tokens.reduce((acc, cur) => {
            acc.push(cur); 
            acc.push( at.shift() )
            
            return acc; 
            
            // 这个reduce将会把 tokens 和 at 耦合在一块 
            // ['一', '零', '一']  和 ['百', '十'] 耦合就是: 
            // ['一', '百', '零', '十', '一', undefined]
            // 下一步的两个 filter 就是要剔除多余的项 
        }, []).filter(e => e !== undefined).filter((e, idx, its) => {
            if (e === '零'){
                if (idx === its.length - 1) {
                    // 针对 10 >>>> [一 十 零] 这种情况
                    return false; 
                } else {
                    // 针对 101 >>>> [一 百 零 十 一] 这种情况 
                    its[idx + 1] = null;
                }
            } else if (idx === 0 && e === '一' && its[idx + 1] === '十'){
                // 针对 12 >>>> [一 十 二] 这种情况 
                return false; 
            }
            // 下面还可以再添加。。 不过应该没了。
            return e; 
        }); 
    };

    Simple test Test conversion

    2 4 6

    8 16 32

    ... into

    two

    four eight sixteen thirty-two ...

    // 2 的 n 次方  
    var twotwotwo = n => (
        new Array(n).fill(2).reduce((acc, cur, idx) => {
            acc = acc * cur; 
            return acc; 
        }, 1)
    )
    
    // 打印机 
    var logger = (item, idx) => console.log(`第 ${idx + 1} 个:`, item); 
    
    // test code 
    function test4toHans(n) {
        var res = arrGenerator(n).map(twotwotwo).map(toHans).map(arr2str); 
        res.forEach(logger); 
    }
    Loop through numbers ....from 1 to n
    var main = n => {
        var numbers = arrGenerator(n); 
        
        return numbers.map(toHans).map(arr2str); 
    } 
    Testing


    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-14 10:52:09

    https://github.com/wilon/php-...

    PHP numbers are converted into Chinese character descriptions, and RMB is capitalized

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-06-14 10:52:09

    Supports hundreds of billions of numbers. Modifying the ws array can be infinitely expanded. Modifying the cns array to Traditional Chinese can be used to capitalize RMB

    <?php
    
    function IntToString($num)
    {
        $cns = ['零','一','二','三','四','五','六','七','八','九'];
    
        $ws = ['','十','百','千','万','十','百','千','亿','十','百','千'];
    
        $str = '';
        foreach (array_reverse(str_split((string)$num,1)) as $key => $value) 
            $str .= $ws[$key].$cns[$value];
        $temp = '';//反转字符串
        for($i = strlen($str)-1; $i>=0; $i--)
            $temp .= mb_substr($str,$i,1,'utf-8');
    
        return $temp;
    }
    
    echo IntToString(231231251237);
    ////二千三百一十二亿三千一百二十五万一千二百三十七

    Attached is the idea
    /a/11...

    reply
    0
  • Cancelreply