4

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

Mayank Vadiya
  • 1,437
  • 2
  • 19
  • 32
Adrian P.
  • 5,060
  • 2
  • 46
  • 47

2 Answers2

10

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);
Lars Ebert
  • 3,487
  • 2
  • 24
  • 46
  • Agree at some point but the value 1,423.28 is returned by MySQL from decimal value 1423.28. Shouldn't do something at the DB level? – Adrian P. Mar 20 '14 at 16:11
  • @AdrianP. http://stackoverflow.com/questions/8669212/change-decimal-separator-in-mysql – Royal Bg Mar 20 '14 at 16:13
  • So, you said that's standard output for MySQL even the number is stored as 1423.28? I understood there is nothing to do but replace the comma for thousands separator. Thanks. I learnt something new today! – Adrian P. Mar 20 '14 at 16:18
  • 1
    I resolved like that number_format($balance, 2, '.', ''); – Mateus Galasso Mar 12 '20 at 12:57
1

Following the answer of Lars Evert I used the function number_format like that

number_format($balance, 2, '.', '');

and that solved my problem

Mateus Galasso
  • 320
  • 1
  • 5
  • 14