0

I'm trying to make a webpage, where when the user clicks a payment button, a set amount it subtracted from an existing value in the database table. Just to confirm: My page does do this. But the unexpected behaviour of my code is it subtracts the amount, but it doesn't round it. It rounds it to 16 decimal places and I only want 2. See the image below (the bottom row) to see what I mean.

I have tried using the number_format() and round() functions in PHP but I'm not sure why they don't work. Am I using them incorrectly?

Unexpected behaviour in database table

This is the full code below:

if(isset($_REQUEST['submit'])) {
  $SQL_query = "SELECT ROUND(SUM(Total), 2) AS sum FROM `order_details` WHERE `OrderID` = 95";
  $query_result = mysqli_query($connection, $SQL_query);

  while($row = mysqli_fetch_assoc($query_result)) {
  $total = $row['sum'];
  $number = floatval($total);
  }

  $SQL_Balance = "UPDATE Users SET Balance=(Balance-$number) WHERE UserID = 7";
  mysqli_query($connection, $SQL_Balance);


} 
 
Dharman
  • 30,962
  • 25
  • 85
  • 135
Harry Wok
  • 9
  • 5

1 Answers1

1

To get a two decimal number you can use ROUND with the following query:

UPDATE Users SET Balance=(ROUND(Balance-$number, 2)) WHERE UserID = 7
code-a1
  • 71
  • 1
  • 5