金额转大写文字

2021-08-21
function amountConver($n)
{
    $fraction = ['角', '分'];
    $digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    $unit = [ ['元', '万', '亿'], ['', '拾', '佰', '仟']  ];
    $head = $n < 0? '欠': '';

    $n = abs($n);
    $s = '';

    for ($i = 0; $i < 2; $i++)
    {
        $s .= preg_replace('/零.*/', '', $digit[bcmod((int)explode('.', $n * 10 * pow(10, $i))[0], 10)] . $fraction[$i]);
    }
    $s = $s ?: '整';
    $n = floor($n);

    for ($i = 0; $i < 3 && $n > 0; $i++)
    {
        $p = '';
        $l = 0;
        for ($j = 0; $j < 4 && $n > 0; $j++)
        {
            $q = $digit[$n % 10];
            if ($q == '零') {
                if ($l == 0) {
                    $p = '零' . $p;
                }
                $l++;
            } else {
                $p = $digit[$n % 10] . $unit[1][$j] . $p;
            }
            $n = floor($n / 10);
        }
        $s = preg_replace(['/(零.)*零$/', '/^$/'], ['', '零'], $p) . $unit[0][$i] . $s;
    }
    return $head . preg_replace(['/(零.)*零元/', '/^整$/'], ['元', '零元整'], $s);
}

 

{/if}