PHP Developers Cookbook (2nd Edition)
2.3 Working with Numbers That Are Not Float or Integer
Technique
Use the bcmath functions that PHP provides to work with arbitrary-precision numbers: <?php $float1 = "234.5769"; $float2 = "478.34299"; $sum = bcadd ($float1, $float2, 10); print $sum; ?> Comments
The title and the subsequent content of this recipe might be a little misleading. The title implies that we will be dealing with numbers that are neither float nor integer. However, in the example, it is quite clear that the numbers would be classified as floats. But this is just for sanity ”the numbers in the example could be well beyond the range of a float and the bcadd() function would still work. When performing operations on arbitrary-precision numbers, the computer often messes up the results. Therefore, the bcmath functions help you in that they enable you to perform all the regular mathematical operations on floating-point figures. Note that we assign the arbitrary-precision numbers as strings. If we assigned them as simple floating-point numbers, the PHP compiler would quickly truncate them down to the regular precision. So what are the bcmath functions? Here are some uses of the different functions: <?php $num1 = "32.45"; $num2 = "33.94"; // If the scale argument (the third argument) is not // given then all of the bcmath functions will use // an accuracy of 10 decimal places bcscale (10); // $num1 + $num2 accurate to four decimal places $sum = bcadd ($num1, $num2, 4); // $num1 - $num2 accurate to 10 decimal places // (from the default scale, set by bcscale()). $difference = bcsub ($num1, $num2); // $num1 * $num2 accurate to 6 decimal places $multi = bcmul ($num1, $num2, 6); // $num1 / $num2 accurate to 7 decimal places $div = bcdiv ($num1, $num2, 7); // square root of $num1 accurate to 12 decimal places $sqrt1 = bcsqrt ($num1, 12); // $num1 2 accurate to 20 decimal places // This only works when the power is a whole number $exp = bcpow ($num1, 2, 20); // modulus of $num1 and $num2 accurate to 20 decimal places $mod = bcmod ($num1, $num2, 20); // Compare $num1 and $num2 accurate to 4 decimal places if (!bccomp ($num1, $num2, 4)) print '$num1 == $num2'; else print '$num1 != $num2'; ?> |