GibsonFX
GibsonFX

Reputation: 1060

PHP shopping cart calculation

Hi I need to remove 10% from a shopping carts subtotal

Original code:

<?php echo number_format($order->subtotal,2);?>&OID=<?php echo $order->trans_id;?>

I know it's not precise, but would something like this work?

<?php echo number_format($order->subtotal * 0.909090909,2);?>&OID=<?php echo $order->trans_id;?>

Thanks

Upvotes: 0

Views: 374

Answers (3)

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44874

Use sprintf()

$a =  2324.56*0.909090909 ;

echo sprintf('%0.2f',$a);

output // 2113.24

sprintf() will handle the floating point precession which is the best way to handle.

If needs to display the money format for specific locale it could be doing using money_format

$a =  2324.56*0.909090909 ;

$amount =  sprintf('%0.2f',$a);

setlocale(LC_MONETARY, 'en_US');

echo money_format('%(#1n', $amount) . "\n";
output // $2,113.24

Here is an explanation on number_format() -ve value precession issue

http://www.howtoforge.com/php_number_format_and_a_problem_with_negative_values_rounded_to_zero

Upvotes: 1

Satish Sharma
Satish Sharma

Reputation: 9635

try this

$subtotal = $order->subtotal;
$cut_subtotal = $subtotal *(10/100);
$subtotal_new = $subtotal-$cut_subtotal;

Now use this in your code

<?php echo number_format($subtotal_new,2);?>

Upvotes: 0

Bryan
Bryan

Reputation: 3494

that probably would work, but why not just subtract the 10 percent? If that's the goal, why not just do it? keep in mind number_format rounds up, but I expect that's desired.

<?php echo number_format( ($order->subtotal - ($order->subtotal* .1) ) ,2);?>

This is the math that actually subtracts 10% why not use this instead of something that's close?

Upvotes: 0

Related Questions