[thelist] Calculations in JS

Ben Henick persist1 at io.com
Sun Jul 21 09:40:00 CDT 2002


On Sun, 21 Jul 2002, Adrian Fischer wrote:

> In JS I'm doing some calculations and I need to shorten the result down
> to 2 decimals.  The number I am multiplying by is 0.00833333333333 (
> could round up to 0.834)  but I don't want to display a gazillion
> places.  In perl I know how to shorten the displayed figure but not in
> JS.  Can someone help please.

Ummm... instead of multiplying by that float, why not divide by 120?

Well...

// begin script block //

a = // your dividend/product as described above //
b = parseFloat(a);
c = b.toString();
d = c.substring(0,4); // returns 3 decimal places, adjust to suit

// ...And then create the cookie. //

// end script block //

> ...
> multiplied by the figure above.  When the user exits the window (closes it
> with close button or by Xing the window) can I save the updated variable to
> a cookie?

Yes.  Basically, a cookie in JavaScript is a string with a particular
syntax that is then assigned to document.cookie.  Likewise, if you create
the cookie in PHP/ASP/perl and the cookie has been properly scoped,
JavaScript will be aware of its presence.

> When the user opens the window again, can I then get the number of seconds
> difference between the saved variable in the cookie and the current time, do
> the multiplication and then continue on from there?

Yes.  You can array.split() the value of the cookie, and eval() the
particular statement you're looking for.  Use eval() with great caution,
as it's VERY resource intensive.

> Would it also be possible to have the JS interact with a perl script on my
> server to update a counter.  It would be nice to know how many instances of
> this window get passed around.
>
> Have I been to vague here?

Slightly.  Would you in this case be looking for unique visitors, or just
the number of times the window was opened?  In the former case, you'll
want to make a unique value (timestamp hash?) part of the value of the
cookie as well... which JavaScrpt can then either submit as a hidden form,
or perl can retrieve the cookie and read it on its own.


--
Ben Henick
Web Author At-Large              Managing Editor
http://www.io.com/persist1/      http://www.digital-web.com/
persist1 at io.com                  bmh at digital-web.com
--
"Are you pondering what I'm pondering, Pinky?"
"I think so, Brain, but... (snort) no, no, it's too stupid."
"We will disguise ourselves as a cow."
"Oh!" (giggles) "That was it exactly!"





More information about the thelist mailing list