Possible Duplicate:
In JavaScript doing a simple shipping and handling calculation
Many companies normally charge a shipping and handling charge for purchases. Create a Web page that allows a user to enter a purchase price into a text box and includes a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling charge of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minimum shipping and handling charge. The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling charge of $5.00. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box.
<!DOCTYPE>
<html><head>
<title>Project Two</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
/*<CDATA[[*/
var salesPrice = window.prompt("Please Enter Purchase Price?", "");
minShipping = salesPrice * 1.50/100;
maxShipping = salesPrice * 10/100;
(salesPrice <= 25)? totalPrice = salesPrice + minShipping
: totalPrice = salesPrice + maxShipping;
alert(totalPrice);
/*]]>*/
</script>
</head>
I please need to have all my script checked and note that, we’re still in chapter 2 thus (if) statements are not allowed to be used yet.
Thanks.
First of all, your ternary operator seems to be quite repetetive. There is a way to make it shorter:
Then, it is a good habit to declare your variables before you use them using
varkeyword. In this particular case the advice is useless, since the script will be executed in the global scope, so all your variables will end up being global.Your version of script concatenates the result since the return type of
window.promptisString. And when the one tries to add aStringto aNumber, the latter just gets converted into aStringand the concatenation occurs.You can explicitly convert
StringtoNumberby using built-inparseInt(orparseFloat) functions or by adding a plus sign.