Category

PHP

PHP: function number_format issues and solution

By | PHP

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php

$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"