PHP Printf As Float Precision

2019-07-13 15:04发布

问题:

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.

回答1:

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.



回答2:

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

echo printf("%d", 10)

When echois called with an expression, it first evaluate all of the params, then displays them on the screen.

When calling echo printf() function ... it is executed, to get its value. So this result in IMIDIATLY printing "10", and string the result value of the function to be echo-ed.

The return printf("%d", 10) is actually 2, if you check the docs it 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