Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong float formatting in PHP (sprintf, printf)

I was debugging PHP code and found out the following:

$a = 111749392891;

printf('%f', $a);
111749392890.:00000

printf('%F', $a);
111749392890.:00000

printf('%F.2', $a)
111749392890.:00000.2

printf('%F0.2', $a);
111749392890.:000000.2

number_format($a, 2, '.','');
111749392891.00

Only number_format() output looks OK to me. Am I missing something? I'm using PHP 5.3.

like image 469
ambienthack Avatar asked Mar 14 '11 02:03

ambienthack


1 Answers

You are placing the format type modifiers after the format type specifier instead of before. Try this:

printf('%.2F', $a)

As for the odd output, it is possible that your localization settings are doing that. Try running the line below and see what is returned for your local.

echo setlocale(LC_ALL, null);

Try changing your locale to something different to see if the problem goes away. Like so:

setlocale(LC_ALL, 'en_CA.UTF-8');
like image 186
MitMaro Avatar answered Sep 28 '22 08:09

MitMaro