これはうまくいくようです-http://jsfiddle.net/nQakD/。
例としてjQueryを使用しましたが、PHPを知っていれば、簡単にPHPに変換できるはずです。PHPコードも必要な場合は、教えてください。私が作成します。
ここにもコードを貼り付けます-
$(document).ready(function() {
var price = 17.48, people = 4, payment = (price/people).toFixed(2), count=0;
var payments = [];
for(i = 0; i < people; i++) {
payments.push(payment);
}
if(payment*people != price) {
var currentPayment = payment*people;
$(payments).each(function() {
if(currentPayment < price) {
currentPayment = (currentPayment-this).toFixed(2);
var newPayment = parseFloat(this)+0.01;
payments[count] = newPayment.toFixed(2);
currentPayment = parseFloat(currentPayment)+parseFloat(newPayment);
}
else if(currentPayment > price) {
currentPayment = (currentPayment-this).toFixed(2);
var newPayment = parseFloat(this)-0.01;
payments[count] = newPayment.toFixed(2);
currentPayment = parseFloat(currentPayment)+parseFloat(newPayment);
}
count++;
});
}
$(payments).each(function() {
$("#result").append("<b>"+this+"</b><br/>");
});
});
編集:
そしてここに動作しているphpコードがあります-
$price = 13.34;
$people = 4;
$payment = (float)$price/$people;
$payment = 0.01 * (int)($payment*100);
$count = 0;
$payments = Array();
for($i = 0; $i < $people; $i++) {
array_push($payments, $payment);
}
if($payment*$people != $price) {
$currentPayment = $payment*$people;
foreach($payments as $pay) {
if($currentPayment < $price) {
$currentPayment = $currentPayment-$pay;
$currentPayment = 0.01 * (int)($currentPayment*100);
$newPayment = (float)$pay+0.01;
$newPayment = 0.01 * (int)($newPayment*100);
$payments[$count] = $newPayment;
$currentPayment = (float)$currentPayment+$newPayment;
}
else if($currentPayment > $price) {
$currentPayment = $currentPayment-$pay;
$currentPayment = 0.01 * (int)($currentPayment*100);
$newPayment = (float)$pay-0.01;
$newPayment = 0.01 * (int)($newPayment*100);
$payments[$count] = $newPayment;
$currentPayment = (float)$currentPayment+$newPayment;
}
$count++;
}
}
foreach($payments as $payed) {
echo '<b>'.$payed.'</b><br />';
}
編集2:
これでjsの問題が修正されるはずです-http://jsfiddle.net/nQakD/上記のコードも更新されました。
編集3:
PHPコードとJSコードを編集して、すべての例で機能するようにしました-http://jsfiddle.net/nQakD/。