PHP

PHP: function number_format issues and solution

By March 23, 2019 July 15th, 2020 No Comments

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
        }

    }

}