1

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.

Jitendra
  • 584
  • 1
  • 10
  • 28

2 Answers2

1

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
?>
Mohammad Hamedani
  • 3,304
  • 3
  • 10
  • 22
0

Try this

<?php
    $a=4.0;
    $b=4;
    echo sprintf("%.2f", $a+$b);
?>
Neeraj Kumar
  • 3,851
  • 2
  • 19
  • 41
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` -- it should be `printf()` without `echo` every time. – mickmackusa Apr 16 '22 at 02:40