2

我目前正在为我的公司制定支票打印解决方案。打印支票时,您需要从支付的金额中打印出百万、十万、万、千、百、十和单位(英镑/美元/欧元等)。

在 111232.23 的情况下,以下是我在下面编写的代码的正确输出。我不禁感到有一种更有效或更可靠的方法可以做到这一点?有谁知道这样做的图书馆/班级数学技术?

float(111232.23)
Array
(
    [100000] => 1
    [10000] => 1
    [1000] => 1
    [100] => 2
    [10] => 3
    [1] => 2
)

<?php

$amounts = array(111232.23,4334.25,123.24,3.99);

function cheque_format($amount)
{
    var_dump($amount);
    #no need for millions
    $levels = array(100000,10000,1000,100,10,1);
    do{
        $current_level = current($levels);
        $modulo = $amount % $current_level;
        $results[$current_level] = $div = number_format(floor($amount) / $current_level,0);
        if($div)
        {
            $amount -= $current_level * $div;
        }
    }while($modulo && next($levels));

print_r($results);
}

foreach($amounts as $amount)
{
 cheque_format($amount);
}
?>
4

3 回答 3

3

我想你只是重写了PHP 的number_format函数。我的建议是使用 PHP 函数而不是重新编写它。

<?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>
于 2012-07-26T12:17:35.957 回答
3

我不确定 PHP 脚本到底是什么,但如果你有 10000、1000、100、10、1 作为你需要的数量。有多少 10,000 的金额 $ 美元?

floor($dollar/10000)

几千?

floor(($dollar%10000)/1000) 

等等

于 2012-07-26T18:12:01.563 回答
1

这不是问题的答案,但以下内容也分解了小数。

function cheque_format($amount, $decimals = true, $decimal_seperator = '.')
{
    var_dump($amount);

    $levels = array(100000, 10000, 1000, 100, 10, 5, 1);
    $decimal_levels = array(50, 20, 10, 5, 1);

    preg_match('/(?:\\' . $decimal_seperator . '(\d+))?(?:[eE]([+-]?\d+))?$/', (string)$amount, $match);
    $d = isset($match[1]) ? $match[1] : 0;

    foreach ( $levels as $level )
    {
        $level = (float)$level;
        $results[(string)$level] = $div = (int)(floor($amount) / $level);
        if ($div) $amount -= $level * $div;
    }

    if ( $decimals ) {
        $amount = $d;
        foreach ( $decimal_levels as $level )
        {
            $level = (float)$level;
            $results[$level < 10 ? '0.0'.(string)$level : '0.'.(string)$level] = $div = (int)(floor($amount) / $level);
            if ($div) $amount -= $level * $div;
        }
    }

    print_r($results);
}
于 2015-05-23T12:36:02.397 回答