homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Subscribe to WebmasterWorld

Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

Printf float issue weirdness

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

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

$_SESSION['test'] = 1501;
RESULT = 15.015

$j = round(($_SESSION['test']*.01),2);
RESULT = 15.015



 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.


 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.

I printed side by side:

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

and got:

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)

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?

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved