phpmysqlnumerical

PHP number_format returns 1.00


I have stored in MySQL the number as total(decimal 16,2) 1423.28

I get it display from PHP after making some calculations:

function calculate_balance($total){

 //get total paid from another function
 $total_paid = ...

 if ($total_paid == 0){
     return $total;
 }else{
     return $total-$total_paid
 }

} 

 $balance = calculate_balance($total);
 echo number_format($balance, 2); //returns 1.00

I have tried

  number_format((float)$balance, 2);
  number_format(floatval($balance), 2); 

UPDATE

var_dump($balance)

and I got following output.

string(8) "1,423.28" float(152) string(6) "252.00" string(6) "247.50" string(6) "247.50" string(6) "247.50" string(6) "549.90" string(6) "495.00" float(0) string(6) "284.76" float(265)

It's working fine without number_format() for value under 1,000. E.g.: if balance equal 252.00

 echo $balance;

output

252.00


Solution

  • Your function returns 1,423.28? This is not a float, as a float does never contain a comma as a thousands-separator.

    PHP interprets this as 1, because it "breaks" at the comma.

    Remove the comma and you are fine!

    $balance = str_replace(',', '', $balance);