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
penders
9:11 pm on Jan 9, 2011 (gmt 0)
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.
salewit
2:43 am on Jan 10, 2011 (gmt 0)
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.
So I guess at this point I'm just going to stop wondering why, and move on with number_format. Live and learn.
penders
9:34 am on Jan 10, 2011 (gmt 0)
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?