Wednesday 15 January 2014

Rounding and formatting money in PHP -



Rounding and formatting money in PHP -

i'm working on script handles calculating dollar amounts , i'm wondering correct, or suggested way go doing so.

i'm dealing dollar , cents, not fractions of cents. i've seen posts such this give scenarios fractions of cents required, such stocks. don't think need precision, before dismiss advice.

say i'm selling item $9.99 6.5% tax.

$item_cost = 9.99; $tax_percent = 0.0650; //6.5% $tax = $item_cost * $tax_percent; //tax 0.38935 $total = $item_cost + $tax; //total 6.37935

i can't charge user $6.37935. i'm dealing dollars , cents. illustration continued...

$total = 4.401433 $rounded_total = round($total,2); echo $rounded_total; //rounded total 4.4

while know $4.4 same $4.40, can't run through payment processor. "safe" round 2 decimal places first , apply number format 2 decimal places?

$total = 4.401433 $rounded_total = round($total,2); $formatted_total = number_format($rounded_total,2,'.',''); echo $formatted_total; //rounded , formatted total 4.40

is "acceptable" determine amounts due first rounding 2 decimal places , using number format create sure rounded number indeed 2 decimal places?

do not utilize number_format determine decimal places. instead round first. round math function , closely related how business operate. illustration if have business rule saying after 2 decimal discarded, round 2 decimal first. number format simply displaying purposes. illustration add together commas, , add together leading 0 when needed. when save figure create sure round according business need , save in db (as final figure)

php

No comments:

Post a Comment