PHP Float转换失败,返回1

时间:2019-11-01 05:09:05

标签: php laravel

我有一个函数,该函数使用1725.00返回number_format(value,2)的值。因此,现在当我将其转换为float时,它会得到1,与intintValuefloatValue相同。甚至我尝试乘以100来获得int的值,但它给出了A non well formed numerical value的错误。有人知道这是怎么回事吗?

$balance = (float) currentBalance($user_id); // currentBalance gives a value of 1725, but (float) gives makes the value 1.
print_r($balance); die; //gives 1.

我正在使用PHP 7.0+Laravel 5.8

1 个答案:

答案 0 :(得分:2)

您的问题是number_format返回一个字符串,其中插入了千个分隔符的逗号,因此函数的返回值为1,725.00。当您尝试将其强制转换为浮点数时,PHP会到达逗号为止并说它不再是数字,因此返回1

如果您需要currentBalance返回的格式化字符串,最好的选择是使用

$balance = (float)str_replace(',', '', currentBalance($user_id));

否则,将对number_format的调用替换为对round的调用,以使currentBalance返回一个数字值。

相关问题