jae-jae
7/19/2016 - 3:58 AM

PHP代码片段

PHP代码片段

<?php
/**
 * 把金额转换成人民币大写
 */
 function getCapitalCny($price) 
 {
        if($price > 999999999999999) {
            throw new ErrorException('Amount out of range');
        }

        $numbers = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
        $units_integer = ['元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟', '万', '拾', '佰', '仟'];
        $units_decimal = ['角', '分'];
        $cny = [];
        $_n = 0;

        list($integers, $decimals) = explode('.', number_format($price, 2, '.', ''));
        foreach(array_reverse(str_split($integers)) as $i => $n) {
            if($i > 0 && !($i % 4) && in_array($cny[0], $units_integer)) {
                array_shift($cny);
            }
            $_cny = $n > 0 || (!($i % 4) && $integers) ? ($n > 0 ? $n : null) . $units_integer[$i] : (!$_n && !$n ? null : $n);
            if($_cny !== null) {
                array_unshift($cny, $_cny);
            }
            $_n = $n;
        }
        if($decimals > 0) {
            foreach(str_split($decimals) as $i => $n) {
                if($n > 0) {
                    array_push($cny, $n . $units_decimal[$i]);
                }
            }
        } else {
            if($integers == 0) {
                array_push($cny, $numbers[0] . $units_integer[0]);
            }
            array_push($cny, '整');
        }

        return str_replace(array_keys($numbers), $numbers, implode('', $cny));
    }