Actually, I want to add two number and the result should be in double.
<?php
$a=4.0;
$b=4;
echo $a+$b
?>
expected output will be 8.0 but it gives result 8. I'm new to PHP.
Actually, I want to add two number and the result should be in double.
<?php
$a=4.0;
$b=4;
echo $a+$b
?>
expected output will be 8.0 but it gives result 8. I'm new to PHP.
Actually it's worked correctly and $a+$b
is float, but because it's 8.0, showing 8. You can use number_format()
function to add fixed decimal point to numbers.
<?php
$a=4.0;
$b=4;
echo $a+$b// Ouput: 8
var_dump($a+$b); //Output: float(8)
echo number_format($a+$b, 1); //echo with one decimal: 8.0
?>
You can test it with other numbers:
<?php
$a=4.1;
$b=4;
echo $a+$b// Ouput: 8.1
var_dump($a+$b); //Output: float(8.1)
echo number_format($a+$b, 1); //echo with one decimal: 8.1
?>
Try this
<?php
$a=4.0;
$b=4;
echo sprintf("%.2f", $a+$b);
?>