[Javascript] Math

Ben Curtis Quixote at LaMancha.org
Thu Aug 16 15:01:48 CDT 2001


> Thanks so much. Works like a charm. I even adjusted the function so
> that I could pass the Price and Discount to the function [fTotal =
> tixPrice(fields[0],fields[1],fields[2])] so if I ever change the price and
> discount in the database it will automatically handle the function.
> 
> function tixPrice(Qty,Price,Disc) {
> var Discounted = parseInt((Qty) /3) *(Disc);
> var RegPrice   = (parseInt(Qty) %3) *(Price);
> return (Discounted + RegPrice);
> }

You might want to throw in another argument:

function tixPrice(Qty,Price,Req,Disc) {
    var ReqForDisc = (Req) ? Req : 1;
    var Discounted = parseInt((Qty) /ReqForDisc) *(Disc);
    var RegPrice   = (parseInt(Qty) %ReqForDisc) *(Price);
    return (Discounted + RegPrice);
}

If there is no discount for buying lots, then you just pass the quantity and
price -- and ReqForDisc will be set to 1 so the %ReqForDisc doesn't gum up.

price = tixPrice(34,2.5);

Otherwise, also pass the required lot size for the discount, and the
discounted price:

price = tixPrice(34,2.5,5,2); // buy 4, get the fifth free!


> What is Math.floor?

It takes a number and throws out the decimal, reducing the number to the
next lowest integer. Nearly the same result as parseInt() but parseInt will
convert a string into a number for you. I suspect that was the problem you
had with that code: form field values are strings until you parseInt or
parseFloat them.

Math.ceil() is also useful: discards the decimal by going up to the next
highest integer. (My definitions aren't perfect: neither floor nor ceil will
change the value at all if the value is an integer.)

--
+Ben Curtis

"On the other side of the screen, it all looks so easy."









More information about the Javascript mailing list