Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 13 ■ SPL EXCEPTIONS^197

As you can see, on my system, PHP can handle arithmetic up to three decimal points, after
which, it goes into floating-point inebriation.
If you were writing a telephone billing system that deals in fractions of a cent, you would
need to be wary of this effect. Otherwise, the results wouldn’t be consistent, and the world
would come to an end (OK, maybe not that extreme, but it would be bad).
Any function that will result in operations on high-precision floating points should throw
an UnderflowException exception if it cannot reasonably complete the operation without a loss
of precision. Listing 13-12 demonstrates using UnderflowException.

Listing 13-12. Using UnderflowException

function scale($a) {
return strlen(strstr($a, '.'))-1;
}

function sum($a, $b) {
if((scale($a) > 3) || (scale($b) > 3)) {
throw new UnderflowException("Input scale exceeded");
}
return $a + $b;
}

echo sum(1,-0.9). "\n";
echo sum(1,-0.99). "\n";
echo sum(1,-0.999). "\n";
echo sum(1,-0.9999). "\n";

0.1

0.01

0.001

Fatal error: Uncaught exception 'UnderflowException'
with message 'Input scale exceeded' in listing12.php:10
Stack trace:
#0 listing12.php(19): sum(1, -0.9999)
#1 {main}
thrown in listing12.php on line 10

It is important that programmers understand the precision limits of the code they write
and that they throw the proper underflow exceptions when the limits are reached. If you do not
watch out for these effects, downstream damage can occur. Additionally, these types of errors
can be exceedingly difficult to trace back to the offending routine.

McArthur_819-9C13.fm Page 197 Thursday, February 28, 2008 7:53 AM

Free download pdf