ambienthack
ambienthack

Reputation: 459

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.

Upvotes: 6

Views: 7516

Answers (1)

MitMaro
MitMaro

Reputation: 5927

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');

Upvotes: 14

Related Questions