Why use BC-Math Library in CakePHP

We faced a big problem when we were working on a CakePHP3.x project, which involved a lot of mathematical calculations & we needed to store the actual values coming from the calculations.

The issue arose when we tried to store decimal numbers with more than 8 decimal points. In that case, CakePHP was not storing actual decimal values into the database. Normally CakePHP can’t handle it.


CakePHP rounds off the decimal points while inserting the data into the Database(DB), which leads to mismatching the actual value.

When a calculation is done on more than 8 decimal points or more than decimal points length which is defined in the database field.

For example, there is a column into a table called “total_amount”, whose data type is ‘decimal’ and its length is (15,8). After calculation, the total_amount is 629.7869073456. When we store the value in the DB, the value will become 629.78690735 or 629.78690740. When the 8th point of the decimal is valuable, then rounding off will make a big difference in calculation.

Enabling PHP BC Math library php.ini file .


1. Change the DB fields data type which stores the values to varchar rather than decimal or float. This will store the exact value.

2. Enable BC-Math library in PHP. Using this library, we can calculate any decimal number point value without round off or any loss of value.

3. Rather than using the general methods of add, subtract, multiply or divide. Use all the math functions for calculations. e.g. bcadd(), bcsub(), bcmul(), bcdiv() .

After going through many blogs and lots of R&D we finally found this solution. We don’t want to work on CakePHP core files because that’s, offcourse, a bad practice. But in this solution, you have to enable BC-Math library in PHP ini.

That may be a problem if you don’t have access to Server PHP configuration. So, you are more than welcome to come up with a solution where this problem can be solved without enabling PHP core library file.

For more such out of the box solutions for your project talk to us .

written by
Sambit Kumar Sahoo
Sambit Kumar Sahoo Senior Web Developer (PHP)