»
S
I
D
E
B
A
R
«
PHP number_format gotcha
December 19th, 2009 by Andrew McCombe

Be careful when doing any kind of calculations with numbers that have been passed through PHP’s number_format function as they can lead to unexpected results. The problems lie with the thousands separator (or the decimal separator if you use anything other than ‘.’). Here’s an example:

andrew@adele:/$ php -a
Interactive shell
 
php > $number = 1234.56;
php > echo $number;
1234.56
php > $number = number_format($number, 2);
php > echo $number;
1,234.56
php > echo $number * 100;
100
php >

The issue is that the calculation ignores everything after the thousands separator ‘ , ‘.


Comments are closed

»  Substance: WordPress   »  Style: Ahren Ahimsa