Skip to content
PHP Logo

How can rounding errors be avoided when performing calculations involving monetary values in PHP?

Rounding errors can be avoided when performing calculations involving monetary values in PHP by using the `bcmath` extension, which provides arbitrary precision arithmetic. This extension allows for precise calculations without the risk of rounding errors that can occur with floating-point arithmetic.

php
// Using the bcmath extension for precise calculations with monetary values
$value1 = '10.25';
$value2 = '5.75';

$sum = bcadd($value1, $value2, 2); // Add the two values with 2 decimal places precision
$diff = bcsub($value1, $value2, 2); // Subtract the two values with 2 decimal places precision

echo "Sum: $sum\n"; // Output: Sum: 16.00
echo "Difference: $diff\n"; // Output: Difference: 4.50