PDA

View Full Version : script with semi-complex math... help


Ricky158
12-02-2002, 05:07 AM
I want to make a price finder thing. It is based on how much of the item the person wants.

For every 5 items, you deduct $1. So the cost for 6 items is $5. 3 items is $3, because 5 cannot go into 3 and get more than 1.

MORE EXAMPLES: 23 = $19 -- 5 goes into 23 4 times. 23 minus 4 equals 19.
48 = $39 -- 5 goes into 48 9 times. 48 minus 9 equals 39.

if it is an exact multiple of 5, like 30, you add $0.50 to the price of the number below it. so 30 would be like doing 29 = $24.50

I don't know how to write a script like this, someone here probably does.

I want it to be in textbox and button form. So you enter the amount of items in one box, and in the other text box it displays the price, after clicking a button to do the math.

any help at all is greatly appreciated.

thanks,
ricky

glenngv
12-02-2002, 05:42 AM
Try this:

<html>
<head>
<script type="text/javascript">
<!--
function compute(f){
quantity=f.q.value;
if (isNaN(quantity)){
alert("Please enter a valid number!");
f.q.focus();
return;
}
rem = quantity % 5;
additional = (rem==0)?0.5:0;
price = (4*quantity + rem)/5 + additional;
f.p.value=price;
}
//-->
</script>
</head>
<body>
<form>
Quantity: <input name="q" /><br />
Price: $<input name="p" readonly="true" /><br />
<input type="button" value="Compute" onclick="compute(this.form)" />
</form>
</body>
</html>

beetle
12-02-2002, 06:42 AM
or this<html>
<head>

<script language="javascript">

function doTotal(f) {
f.total.value = currency(calcTotal(f.quantity.value),1,1);
}

function calcTotal(qty) {
var unitPrice = 1.00;
var groups = 5;
var extra = .50;
var total;

total = qty * unitPrice;
total -= parseInt(qty/groups);
if (qty % groups == 0) total += extra;
return total;
}

function currency(anynum, grouping, dollar) {
anynum = anynum.toString();
var point = anynum.indexOf(".");
var result = Math.round(anynum*100)/100;

if (point == -1)
result = parseInt(anynum) + ".00";
else {
var decimals = anynum.substring(point+1);
if (decimals.length == 1) result = anynum + "0";
}

if (grouping) {
point = result.indexOf(".");
var dollars = result.substring(0, point);
var cents = result.substring(point);
var commas = parseInt(dollars.length / 3);
var temp = new Array();
for (var i=commas; i>=0; i--) {
if (dollars.length > 3) {
temp[i] = dollars.substring(dollars.length-3);
dollars = dollars.substring(0,dollars.length-3);
}
else {
temp[i] = dollars;
}
}
dollars = temp.join(",");
result = dollars + cents;
}

if (dollar)
result = "$ " + result;

return result;
}

</script>
</head>

<body>

<form>
Enter Quantity: <input type="text" name="quantity" size="5" />
<input type="button" value="Calculate Total" onClick="doTotal(this.form);" />
<br />
<input type="text" name="total" readonly="true" />
</form>

</body>
</html>

Ricky158
12-02-2002, 10:31 PM
thanks, both of those work perfectly.

:thumbsup: