Reputation: 44066
Ok so i have a variable named
$total_cost
which is equal to 529700
I need the value to be $5,297.00
this value is coming out of a mysql decimal 10,2 field
I need to now come up with a subtotal of 2% and a shipping of 8.25% based on whether the user is in the state
Lets just assume all the users are from this state, how would i do this via php to preserve the cents
For example this is what i was thinking
$subtotal = $total_cost * 0.02;
$shipping = $total_cost * 0.0825;
$new_total = $total_cost + $shipping + $subtotal;
but i get $0 when i print this...any ideas why
<?php print "$". $new_total; ?>
Upvotes: 0
Views: 104
Reputation: 125728
You have to convert it to a floating point number when you calculate the percentage, or the integer rounds down to 0.
$subtotal = $totalcost / 100.0 * 0.02;
$shipping = $totalcost / 100.0 * 0.0825;
$newtotal = $totalcost / 100.0 + $subtotal + $shipping;
Upvotes: 0
Reputation: 48287
This looks like it might help you. Grab the number, divide by 100, do your calculations and format it during output.
<?php print "$".number_format($new_total/100, 2); ?>
Note that you can combine the math into a single statement:
$new_total = $total_cost * 1.1025; // just add the numbers together and add 1
Upvotes: 0
Reputation: 21563
I don't obtain that result when testing your code...
php > $total_cost=529700;
php > $subtotal = $total_cost * 0.02;
php > $shipping = $total_cost * 0.0825;
php > $new_total = $total_cost + $shipping + $subtotal;
php > print "$". $new_total;
$583994.25
Are you sure that the initial value is what you expected?
Upvotes: 2
Reputation: 29160
You need to see where this code breaks down, and that the values you think you have are actually there.... What does this output look like?
echo "Total: ".$total_cost."<br />";
$subtotal = $total_cost * 0.02;
echo "Sub: ".$subtotal . "<br />";
$shipping = $total_cost * 0.0825;
echo "Shipping: ".$shipping . "<br />";
$new_total = $total_cost + $shipping + $subtotal;
echo "New Total: ".$new_total . "<br />";
Upvotes: 0