-1

I don't understand the result ?! 29.85-3.5527136788005E-15 PHP bug ? Same result with floatval or cast can you help me ? The simple example code here :

<?php 
$new = array('29.85');
$two = array('6.95','9.95','12.95');
$montantTotal = 0 ;
foreach ($two as $lignes) {
    $montantTotal += floatval($lignes);
    }
echo $montantTotal ;
$result = $montantTotal - floatval($new[0]);
echo $result;
  • 1
    [Read, learn and understand](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) This is common to all languages that use IEEE-754 – Mark Baker Nov 03 '17 at 11:19
  • 1
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – apokryfos Nov 03 '17 at 11:20
  • The E means `exponential` and you're getting a very small number because of how borked floating point math is. To correct the issue, you must use [number_format](http://php.net/manual/en/function.number-format.php) to get a correct display. – IsThisJavascript Nov 03 '17 at 11:21
  • If you had a person write down the result of `1/3` on a piece of paper they'd probably write something like `0.3333333` but because the paper doesn't fit all the digits, when they then do a `0.333333 * 3` they don't get 1 as they should but something like `0.9999999`. Is maths broken? No, we just don't have enough paper. – apokryfos Nov 03 '17 at 11:24
  • Computers can't store the exact values of many float numbers like the result of (1/3). that is why you should keep a rounding function and float comparison function as your companions when you are doing float arithmetic stuff – Accountant م Nov 03 '17 at 11:28
  • see this answer [https://stackoverflow.com/a/42833596/5407848](https://stackoverflow.com/a/42833596/5407848) – Accountant م Nov 03 '17 at 11:51

2 Answers2

3

You can use number_format

Syntax

string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )

Example

    $new = array('29.85');
    $two = array('6.95','9.95','12.95');
    $montantTotal = 0 ;
    foreach ($two as $lignes) {
        $montantTotal += (float)$lignes;
        }
   // echo $montantTotal ; echo "<br>";
    $result = number_format($montantTotal,8,".","") - number_format((float)$new[0],8,".","");
    echo $result;

Output

0
shubham715
  • 3,324
  • 1
  • 17
  • 27
0

Result is very small. It use scientific notation.

 $montantTotal =  29.85
 $result = -3.5527136788005E-15
newman
  • 424
  • 2
  • 12