PHP: function number_format issues and solution

March 23, 2019June 13th, 2021No Comments

We have bcmath too! Don’t forget about that.

Note: money_format is deprecated now.

Following is not really an issue but we could run into a trap if we don’t be careful about it. Bottom line is to understand that number_format returns string and when any arithmetic operation is performed to it, we could end up with huge problems.

We can use round but round for 45.20 will give 45.2. Even when we asked for 2 decimals. money_format returns string as well. I guess it will be best to use round for calculations and for displaying numbers use number_format or money_format.

The thing with number_format besides the string issue is, client could ask for \$15 instead of \$15.00. However number_format will stick to the the decimals as instructed.

A solution to the zeroes could be a filter.

 12345 Vue.filter('removeZeroes', function (value) {     if (value) {         return value.replace('.00', '');     } });
 123456789101112131415161718192021222324 \$a = number_format(100000, 2); \$b = number_format(100000, 2); \$c = \$a + \$b; // 200 // TODO: FIXME: REMOVE THIS var_dump(\$c); \$a = round(100000, 2); \$b = round(100000, 2); \$c = \$a + \$b; // float(200000) // TODO: FIXME: REMOVE THIS var_dump(\$c); \$c = 45.1261423; echo money_format('%i', \$c); // 45.13 setlocale(LC_MONETARY, 'en_CA'); var_dump(money_format('%i', \$c)); // string(13) "CAD200,000.00"

The other solution

 123456789101112131415161718192021 namespace App\Libraries; class NumberFunctions {     public static function is_decimal(\$val)     {         return is_numeric(\$val) && floor(\$val) != \$val;     }     public static function handle_money_display(\$amount, \$currency = "\$")     {         if (self::is_decimal(\$amount)) {             return \$currency . number_format(\$amount, 2);         } else {             return \$currency . number_format(\$amount, 0);         }     } } 