如何舍入金额正确? #Update 1

I have a little problem with round() in php. I don't know, if I really make it correct. (it is an order system)

$amount can be decimal 14,8 $price can be decimal 10,5 (in the database)

I am using the following rounding at this moment The $price is for one $amount

function round_amount($amount) {
  return (float) round($amount, 8);
}

function round_price($amount) {
  return (float) round($amount, 5);
}

//if some one have more decimal chars like 10.000000009
round_amount(10.000000009); //will be 10.00000001

//if some one have more decimal chars like 10.000009
round_price(10.000009); //will be 10.00001

//also this is possible
round_price(round_amount(10.000000009)*round_price(10.000009))

Is this way correct to use round? Some user are using more than 16 decimals. I am deducting / adding the results in the user database.

But I see, that some user have about 5-10 cents too much!

Is the only way to resolve this, to allow ONLY 8 and 5 decimals? And warn the user, if he tries to use more? But than I will get an problem with the round_cur(round_amount(10.000000009)*round_cur(10.000009))

I hope some one understand what I am meaning, or can tell me, if my way to round is correct.

Update 1

$amount = 10.12398413498579889173459873;
$price = 5.1938457198347695;

echo round_cur(round_amount($amount)*round_cur($price))."<br />";
echo round_cur($amount*$price);

//returns
//52.58245
//52.58241

Interesting!

I think you way is correct, but depend on your situation as you mentioned, those two formulas return different values and you are the one as the manager of the project which system is better for you (you should think about what is best for you and what is best for user and make up your mind and see if you choose either, what would be the trade of) and for this situation i recommend the first methid

round_price(round_amount(x)*round_price(y))

And for your problem a good notice or warning should do it. Give an example for user.

Why not keep the actual value from the database cached and then have a separate variable for display. In that way all of the calculations can be done on the cached, correct, value while maintaining a clean UI. Just make sure to update the displayed variable each time the cached variable is updated.

Also, always apply math before doing any rounding. Multiplying two exact numbers is much more accurate than multiplying two rounded numbers. This applies for every operation in mathematics. So add, subtract, divide, multiply and then round, but never use that rounded number for another formula. Use the previous exact number.