Welcome to WebmasterWorld Guest from 54.162.240.235

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Printf float issue weirdness

     
5:38 am on Jan 9, 2011 (gmt 0)

10+ Year Member



What is going on here? Why is printf not behaving correctly? How do I display 1501 as 15.01?

session_start();
$_SESSION['test'] = 1501;
printf("%01.2f",($_SESSION['test']*.01));
RESULT = 15.015

$j = round(($_SESSION['test']*.01),2);
printf("%01.2f",$j);
RESULT = 15.015
9:11 pm on Jan 9, 2011 (gmt 0)

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Your code works OK for me, both output '15.01'. The only difference in my test is I use $TEST in replace of the session variable, but I can't see that that would make a difference!?

The only thought is that the 'f' type specifier is "locale aware" (according to the manual [uk2.php.net]) - so this could explain it. Try the '%F' type specifier.
2:43 am on Jan 10, 2011 (gmt 0)

10+ Year Member



Nope, tried "F" and still did it. While reading my O'Reilly PHP book last night (I'm a beginner), they said printf is a rarely used function and they more or less said to use number_format() which I never even heard of.

I printed side by side:

$_SESSION['test'] = 1501;
$j = round(($_SESSION['test']*.01),2);
printf("%01.2f",$j);
print "<br>".number_format($j,2);


and got:
15.015
15.01

So I guess at this point I'm just going to stop wondering why, and move on with number_format. Live and learn.
9:34 am on Jan 10, 2011 (gmt 0)

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



Hhhmm, that seems odd. printf() might be a lesser used function, but its sister function sprintf() [uk2.php.net] - which uses the exact same syntax and AFAIK behaves the same as printf(), but returns a string rather than outputting it directly - certainly is!

printf() / sprintf() certainly come into their own when formatting a string of multiple values or of more complexity. number_format() [uk2.php.net] is also not locale aware in itself.

I'm curious, what version of PHP / OS have you tried this on? Have you tried another server?
 

Featured Threads

Hot Threads This Week

Hot Threads This Month