Liftoff
Liftoff

Reputation: 25432

PHP Printf As Float Precision

I am attempting to use PHP's printf function to print out a user's storage capacity. The full formula looks something like this:

echo printf("%.02f", ($size/(1024*1024))) . " GB";

Given that $size == (10 * 1024 * 1024), this should print out

10.00 GB

But it doesn't. It prints 10.04 GB. Furthermore,

echo printf("%.02f", 10)

results in

10.04


What?! In giving it an integer to convert to a float, it converts 10 to 10.00000009.

How can this be remedied? Obviously, one solution would be to print it out as an integer, but the value will not always be an integer; it may be 5.57 GB, in which case the accuracy of this script is very important.


And umm...

echo printf("%d", 10)

results in

102

Something is very wrong here.

Upvotes: 2

Views: 3824

Answers (2)

d.raev
d.raev

Reputation: 9556

This is to deep, But I will try to explain:

echo printf("%d", 10)

TL>TR: When echo is called with an expression, it first evaluate all of the params, then displays the result on the screen. If some of the expressions print something on the screen when evaluated, you get a this mess.

First thing that happens is printf() it is executed, to get its value. This result in IMMEDIATELY printing "10" on the screen/output.

Then, the return result of printf() is echo-ed, in this case it is "2". If you check the docs printf returns the length of the result string.

So on the screen you see "10","2"

You should really not use Print() and similar function together with Echo.

P.S Here is another gem:
echo 1. print(2) + 3; // result: 214

Upvotes: 0

Liftoff
Liftoff

Reputation: 25432

So apparently printf is not meant to be echoed. At all.

Simply changing the instances of printf to sprintf fixed that problem.


Furthermore, removing the echo, and just running the command as printf("%.02f", 10) does, in fact, print 10.00, however, it should be noted that you cannot append strings to printf like you can with echoing.


If you ask me, PHP should've thrown a syntax error, unexpected T_FUNCTION or something, but I digress.

Upvotes: 3

Related Questions