将浮点数除以 x 个变量

Divide amount of a float over x numbers of variables

我想将总量(例如 4.45)除以动态数量的变量(例如 4。变量的总和应始终是总量的总和。

如果你除以 4 你会得到 1,1125 一轮(1.1125, 2) 你会得到 1.11。 4 * 1.11 = 4.44。剩余的 0,01 可以添加到变量的最后数量,因此它将是 1.12。

1) 使用数组而不是单独的变量 2)对数组进行计数和求和

我给你写了一个几乎完全符合你要求的函数(我 return 一个数组)。你可以给出一个数量和你想要 returned 的变量的数量。它总是四舍五入到 2 位小数

<?php
function divideAmount($amount, $numberOfVars){

    $values = [];

    $dividedAmount = $amount/$numberOfVars;

    for($i=1; $i<=$numberOfVars; $i++){
        $values[] = round($dividedAmount,2);
    }

    $newAmount = 0;
    foreach($values as $value){
        $newAmount += $value;   
    }

    if($newAmount != $amount){
        $amountLeft = $amount - $newAmount; 
        $values[$numberOfVars-1] += $amountLeft;
    }

    return $values;
}


$values = divideAmount(4.45, 4);

var_dump($values);

您可以为此使用 array_fill()

$tot   = 4.45;   # sum total
$n     = 4;      # addends number

$values = array_fill( 0, $n-1, round( $tot/$n,2 ) );
$values[ $n-1 ] = round( $tot - array_sum( $values ),2 );

print_r( $values );
echo array_sum($values) . PHP_EOL;

将输出:

Array
(
    [0] => 1.11
    [1] => 1.11
    [2] => 1.11
    [3] => 1.12
)
4.45

phpFiddle demo

首先,用动态数字四舍五入的总数填充 n-1 个项目的数组,然后添加最后一个项目减去现有项目的总和。