📜  php 数字转单词 - PHP (1)

📅  最后修改于: 2023-12-03 15:03:42.465000             🧑  作者: Mango

PHP 数字转单词

在 PHP 中,我们可以将数字转换为对应的英文单词。这种转换对于一些特殊的需求非常有帮助,比如数字金额的大写表述等。

以下是一个示例函数,用于将数字转换为英文单词:

/**
 * 将数字转换为英文单词
 * @param int $number 要转换的数字
 * @return string 转换后的英文单词
 */
function numberToWord($number) {
    $words = array(
        0 => 'zero',
        1 => 'one',
        2 => 'two',
        3 => 'three',
        4 => 'four',
        5 => 'five',
        6 => 'six',
        7 => 'seven',
        8 => 'eight',
        9 => 'nine',
        10 => 'ten',
        11 => 'eleven',
        12 => 'twelve',
        13 => 'thirteen',
        14 => 'fourteen',
        15 => 'fifteen',
        16 => 'sixteen',
        17 => 'seventeen',
        18 => 'eighteen',
        19 => 'nineteen',
        20 => 'twenty',
        30 => 'thirty',
        40 => 'forty',
        50 => 'fifty',
        60 => 'sixty',
        70 => 'seventy',
        80 => 'eighty',
        90 => 'ninety'
    );
    
    if (!is_numeric($number)) {
        return false;
    }
    
    $word = '';
    
    if ($number < 0) {
        $word = 'minus ';
        $number = abs($number);
    }
    
    if ($number < 21) {
        $word .= $words[$number];
    } elseif ($number < 100) {
        $word .= $words[10 * floor($number / 10)];
        $remainder = $number % 10;
        if ($remainder > 0) {
            $word .= '-' . $words[$remainder];
        }
    } elseif ($number < 1000) {
        $word .= $words[floor($number / 100)] . ' hundred';
        $remainder = $number % 100;
        if ($remainder > 0) {
            $word .= ' ' . numberToWord($remainder);
        }
    } elseif ($number < 1000000) {
        $word .= numberToWord(floor($number / 1000)) . ' thousand';
        $remainder = $number % 1000;
        if ($remainder > 0) {
            $word .= ' ';
            if ($remainder < 100) {
                $word .= 'and ';
            }
            $word .= numberToWord($remainder);
        }
    } elseif ($number < 1000000000) {
        $word .= numberToWord(floor($number / 1000000)) . ' million';
        $remainder = $number % 1000000;
        if ($remainder > 0) {
            $word .= ' ';
            if ($remainder < 100) {
                $word .= 'and ';
            }
            $word .= numberToWord($remainder);
        }
    }
    
    return $word;
}
使用方法

要将一个数字转换为英文单词,只需要调用上述函数并传入要转换的数字即可。例如:

echo numberToWord(12345); // 输出 twelve thousand three hundred and forty-five

当然,如果要进行更加复杂的转换,你可以在此基础上进行修改。