警告:number_format()要求参数1为float,在第205行D:\examplep\htdocs\we



我得到了这个:

警告:number_format((要求参数1为float,字符串在D:\examplep\htdocs\website\foodpoint\welcome.php的第205行中给出

这是我在第205行的代码:

<?php
$tot_tapas = number_format($number_of_persons, 2) * number_format($tapas, 2)
?>
<?php
$details = json_decode($obj->details);
$tapas = $number_of_persons = '';
foreach ($details->items as $item) {
foreach ($item->extras as $extra) {
// new
$tapas = $item->service_price;
$number_of_persons = $item->number_of_persons;
// new
?>
<div class="row">
<div class="col kolom1">
<?php echo $extra->quantity; ?>x <?php echo $extra->title; ?>
</div>
<div class="col kolom2">
P/s : €<?php echo $extra->price; ?>
</div>
<div class="col kolom3">
<?php $total = $extra->quantity * $extra->price; ?>
<?php echo '€' . number_format($total, 2); ?>
</div>
</div>
<hr>
<?php

}
}
?>

错误告诉number_format()函数的第一个参数不是float(它应该是(。

您必须将变量强制转换为float。你可以用floatval((或直接铸造

在您的情况下,它是$number_of_persons$tapas,或者两者都是

如果你确定变量有数字作为值,那么你可以这样做:

$tot_tapas = number_format((int) $number_of_persons, 2)  * number_format((int) $tapas, 2)

魔术是类型杂耍,你可以把它投射到int。点击此处阅读更多:https://www.php.net/manual/en/language.types.type-juggling.php

但是,您应该确保变量的类型为integer,并且没有字符串值。

$number_of_persons = 4;
$tapas = 2; 
// => OK
$number_of_persons = "4";
$tapas = "two tapas 2"; 
// => Warning: number_format() expects parameter 1 to be float, string given

您可以使用floatval((。但我想你可以找到哪一个不是float number_ofPersons或tapas。使用gettype((查看哪一个是字符串并修复它。

如果你确定变量有数字作为值,那么你可以这样做:

$tot_tapas = float($number_of_persons) * float($tapas);
$tot_tapas = number_format((float)$tot_tapas , 2, '.', '');

最新更新