I'm working on a script that handles calculating dollar amounts and I'm wondering what is the correct, or suggested way to go about doing so.
I'm dealing with dollar and cents, not fractions of cents. I've seen posts such as this which give scenarios where fractions of cents are required, such as stocks. I don't think I need that precision, but before I dismiss it I would like some advice.
Say I'm selling an item for $9.99 with 6.5% tax.
$item_cost = 9.99;
$tax_percent = 0.0650; //6.5%
$tax = $item_cost * $tax_percent;
//tax is 0.38935
$total = $item_cost + $tax;
//total is 6.37935
I can't charge a user $6.37935. I'm just dealing with dollars and cents. Example continued...
$total = 4.401433
$rounded_total = round($total,2);
echo $rounded_total;
//rounded total is 4.4
While I know $4.4 is the same as $4.40, I can't run this through my payment processor. Is it "safe" to round to 2 decimal places first and then apply number format to 2 decimal places?
$total = 4.401433
$rounded_total = round($total,2);
$formatted_total = number_format($rounded_total,2,'.','');
echo $formatted_total;
//rounded and formatted total is 4.40
Is it "acceptable" to determine amounts due by first rounding to 2 decimal places and then using number format to make sure that rounded number is indeed 2 decimal places?