0

As a computer engineer I am totally aware of how floating point arithmetic works on the CPU (ALU) layer. This is NOT my question. My question is how to accurately subtract two floating point values without having to write hundreds of lines of boilerplate code to do so. In a script language like PHP there MUST be a simple way to do this, right? I mean we are living in the year 2020 and still have to deal with this kind of crap on the software side? Excuse my language.

I have two floats (same values) - one is retrieved from a database and the other one is retrieved via JSON request. Printing the two values with echo results in:

$a = 1865183.4082;
$b = 1865183.408200000000000000;

Now I want to subtract them and obtain the true result (precision of 10 decimals) which is zero. I tried the following three ways:

$res = $a - $b;
// $res = 7.4505805969238E-9
$res = floatval(number_format($a, 10, ".", "")) - floatval(number_format($b, 10, ".", ""));
// $res = 7.4505805969238E-9
$res = bcsub(number_format($a, 10, ".", ""), number_format($b, 10, ".", ""), 10);
// $res = 0.0000000075

I just spent two hours on finding the solution. No success. Please help.

EDIT: Someone closed this question as if I wasn't able to look at all the other questions related to this. My problem is NOT solved and there is no solution in the linked question. Thanks.

mschoenebeck
  • 377
  • 3
  • 12
  • 5
    As soon as you write your floats as floats into your source code, your accuracy is already out the window. You need to write your numbers as string and subtract them as string (using `bcsub`); not format already inaccurate floats to strings. – deceze Dec 21 '20 at 07:37
  • Isn't that exactly what I do in the last line? converting float to string and then using bcsub? Why is the result still 0.0000000075? I don't get it... – mschoenebeck Dec 21 '20 at 20:47
  • I just figured.. printing them with `number_format($a, 10, ".", "")` and `number_format($b, 10, ".", "")` results in `1865183.4082000074` and `1865183.4081999999` because at some point they became floats in my code...gosh, this sucks.. – mschoenebeck Dec 21 '20 at 21:11
  • Anyway, your comment basically answers my question. It just sucks, that in a language like PHP where you are not really in control of the types you still have to deal with this kinda problem related to types... whatever.. thanks. – mschoenebeck Dec 21 '20 at 21:13

1 Answers1

-1

Please round the result:

$a = 1865183.4082;
$b = 1865183.408200000000000000;
echo $result = round($a - $b, 2);