Search code examples
phpprecision

Using PHP floatval adds undesired trailing numbers behind decimal places


I am having a problem with php conversion from string to float

In some cases, if I do:

floatval("8.80")

I get:

8.800000000000001

I have struggled with round(x,1), number_format, etc, but to no avail

What am I getting wrong here?


Solution

  • By using number_format will help to resolve your issue

    <?php
        $number = 8.800000000000001;
        $precision = 1;
        $number = intval($number * ($p = pow(10, $precision))) / $p;
        echo number_format((float) $number, $precision, '.', ''); 
    ?>
    

    enter image description here