[ale] PHP rounding in an imagestring
Phil Turmel
philip at turmel.org
Sun Dec 28 15:41:08 EST 2014
On 12/28/2014 11:24 AM, William Bagwell wrote:
> Is this even possible? Warning, dove in and spliced code snippets from
> various sources with zero experience:-O Must say PHP is an order of
> magnitude easier to learn than Perl. And two orders less headache inducing!
>
> On a forum where many of the regulars have signature banners with statistics
> and stuff related to the forums topic. Wanting one that is totally unique so
> started with
> $now = time(); // or your date as well
> $your_date = strtotime("2010-01-01");
> $datediff = $now - $your_date;
> echo floor($datediff/(60*60*24));
> modified the forth line to match some code found elsewhere.
> imagestring($im, 3, $left_margin, 18, $datediff/(60*60*24), $black);
> Amazingly it works but returns 8 unneeded decimal places. Nothing I tried
> would remove them and in searching I found a completed script on a rival
> forum for the same topic. They declare every thing first so no math occurs
> inside an imagestring. Probably the route I need to take but want to ask
> before abandoning my much shorter script.
What you are experiencing is implicit conversion. The imagestring
function is defined to take a *string* to turn into an image, and you
are giving it a number. Unlike C or other formally-typed languages, PHP
doesn't mind, it just converts the result to a string for you.
What you want is to deliver a *formatted* string to the imagestring
function. PHP offers a variety of functions that'll do that, but the
simplest is probably what you want:
http://php.net/manual/en/function.number-format.php
So, wrap your expression with the number_format() function to limit the
decimal places. For two decimal places, like this:
imagestring($im, 3, $left_margin, 18,
number_format($datediff/(60*60*24), 2), $black);
Enjoy!
Phil
More information about the Ale
mailing list