I have the following lines of code to check the balance of the user.

 $balance = query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
 $balance = number_format($balance[0]["cash"],2);

And the following code to check the total cost of purchasing the stocks

 $total = number_format($share["price"] * $_POST["quantity"],2);

But when I compare these two variables via

 if($total > $balance)

it does not work as I intended. For example, if a user with balance of $10,000 tries to purchase 100 stock with symbol 'FREE'(which costs 0.03 (2d.p)), the $total seems to be greater than the $balance, thus an error occurs. Furthermore, when the number of stocks is 10 it seems to work. I even tried to convert the $_POST["quantity"] to integer first and then calculate the total but it still gave out the same result.

Any help would be appreciated!! Cheers

  • I would print the values of my variables and try to figure out what's wrong!
    – kzidane
    Dec 4 '15 at 7:35
  • I have tried that as well. The values are printed out correctly but when I subtract them together i.e $balance - $total, it seems like the value of $balance is always equal to 1 thus it gives out negative value.
    – James C
    Dec 4 '15 at 7:49
  • Also, if I convert the $balance to float and print out its value, it is always equal to 1... I really need some help here :(
    – James C
    Dec 4 '15 at 8:31

Yes!! I think I know what the problem was. As I was using number_format function, the values of $total and $balance had commas to separate every group of thousands. Thus when I implemented any arithmetic operations, PHP read the $balance until an invalid character appears. (e.g if $balance = 1,000 during arithmetic operations PHP "revalued" the variable as 1 as any integers after the comma is unread). If any of you disagree and has another explanation, I would appreciate it :)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .