dooode
dooode

Reputation: 197

multiplying a float, getting wrong answer (php)

I have a float that is return data from a cURL call, that I would like multiply by 0.25% (a fee) and then sum (add fee to subtotal)

code:

var_dump(var_dump($obook['Bid']);
echo number_format(($obook['Bid'] *= 0.0025) + $obook['Bid'], 8););

output:

float(0.01191616)
0.00005958

I am able to get the percentage amount, but not add it to the subtotal.

How to I calculate a fee and sum, to a float?

i.e. 0.01191616 * 0.0025 = $fee

$fee + 0.01191616 = $new_grand_total

UPDATE: This is not correct:

$commis = $obook['Bid'] *= 0.0025;
var_dump(number_format($commis, 8));

output:

string(10) "0.00002976"

Upvotes: 1

Views: 1258

Answers (2)

Barmar
Barmar

Reputation: 780861

$obook['Bid'] *= 0.0025

means to multiply the variable by 0.0025 and then put that result back in $obook['Bid']. Then when you add $obook['Bid'] to it, you're just doubling that result.

In other words, your code is equivalent to:

$obook['Bid'] = $obook['Bid'] * 0.0025;
echo number_format(2 * $obook['Bid'], 8);

Because of this, you're losing the original value of $obook['Bid'], replacing it with just the fee, and then adding the fee to itself.

You should use *, not *=, if you don't want to update the variable.

$new_grand_total = $obook['Bid'] * 0.0025 + $obook['Bid'];

You can also use high school algebra to realize that x * y + x is equivalent to x * (1+y), so you can do:

$new_grand_total = $obook['bid'] * 1.0025;

Upvotes: 1

BeetleJuice
BeetleJuice

Reputation: 40886

do this instead:

$obook['bid'] *= 1.0025

Upvotes: 0

Related Questions