PHP number_format返回1.00

时间:2014-03-20 15:41:14

标签: php mysql numerical

我在MySQL中存储的数字为总数(十进制16,2)1423.28

我在进行一些计算后从PHP中显示它:

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

我试过了

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

更新

var_dump($balance)

我得到了以下输出。

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)

如果价值低于1,000,那么没有number_format()就可以正常工作。 例如:如果余额等于252.00

 echo $balance;

输出

252.00

2 个答案:

答案 0 :(得分:6)

您的函数返回1,423.28?这不是浮点数,因为浮点数永远不会包含逗号作为千位分隔符。

PHP将此解释为1,因为它"中断"在逗号。

删除逗号,你没事!

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

答案 1 :(得分:0)

answerLars Evert之后,我像这样使用了number_format函数

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

那解决了我的问题