How to get double value in 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.

3 answers

  • answered 2017-06-17 18:07 scaisEdge

    You can use the proper cast

    echo (doubleval)( $a+$b); 
    

    or floatval

  • answered 2017-06-17 18:07 NeErAj KuMaR

    Try this

    echo sprintf("%.2f", $a+$b);
    

  • answered 2017-06-17 18:07 Mohammad Hamedani

    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
    ?>