-1

My code is very simple, for example, my php version is 5.5.11, this is my sample code:

$result = round(($num / 100), 2); // 0.070000000001
$result = $num / 100; // 0.070000000001

I get the $result is 0.070000000001, and if $num = 3, the $result is correct. And I used var_dump($num), the type is the float. how can I fix it?

edit

I found the reason, but I'm not sure the detail. I use Codeigniter, and I load a library PHPExcel, this is third party lib, when I load it, and I will have this problem, but I'm not sure the reason detail.

lighter
  • 2,808
  • 3
  • 40
  • 59

2 Answers2

1

As I wrote in comment it is connected with how floats are stored in memory

From manual:

Never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

http://php.net/manual/en/language.types.float.php

I don't know what you want to do with this float variable but if you want to compare then you need some $epsilon

if(abs($a-$b) < $epsilon)

if you want to round then probably you should ignore last digit. number_format() seems like better solution.

Robert
  • 19,800
  • 5
  • 55
  • 85
0

This is the issue with floating numbers.

You can even try bccomp

    $a = 1.2 * 3;
    if (bccomp($a, 3.6) === 0) {
        echo 'equal';
    } else {
        echo 'not equal';
    }

    //echoes equal

    echo "----------------------";
    $a = 1.2 * 3;
    if ($a == 3.6) {
        echo 'equal';
    } else {
        echo 'not equal';
    }

    //echoes not equal
Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41