user3476345
user3476345

Reputation: 331

Rounding and formatting money in PHP

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?

Upvotes: 4

Views: 7318

Answers (1)

xelber
xelber

Reputation: 4637

DO NOT use number_format to determine the decimal places. Instead Round it first. Round is a math function and closely related to how the business operate. For example if you have a business rule saying anything after 2 decimal is discarded, round it to 2 decimal first. Number format is merely for displaying purposes. For example to add commas, and to add leading 0 when needed. When you actually save a figure make sure to round it according to the business need and then save in DB (as a final figure)

Upvotes: 6

Related Questions