Skip to content
Advertisement

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement