将数字分解为数千、数百等


Break down number into thousands,hundreds,etc

我目前正在为我的公司准备一个支票打印解决方案。打印支票时,您需要打印所支付金额的数百万、数十万、数万、数千、数百、数十和单位(英镑/美元/欧元等)。

在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);
}
?>

我想您只是重新编写了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
?>

我不确定PHP脚本会是什么,但如果你有10000、1000、100、10、1作为你需要的东西。多少10000美元?

floor($dollar/10000)

几千?

floor(($dollar%10000)/1000) 

等等。

这不是问题的答案,但下面也对小数进行了分解。

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);
}