PDA

View Full Version : Error with IF statements



levi15791
Oct 11th, 2010, 01:57 PM
<html>
<script>
// Author: L Freeman
// Date: 11/10/10
// Purpose: Calculate student discount/vat reductions

var price = 0;
var vat = 17.5;
var discount = 10;
var reduction = 0;
var deduction = 0;
var reductionVAT = 0;
var priceDiscount = 0;
var priceNoVATDiscount = 0;

// Calculate new price

price = prompt("Enter price:");

// Calculate reduction
reduction = (price/100) * discount;
priceDiscount = (reductionVAT-reduction);
priceNoVATDiscount = (price - reduction);

// Calculate vat deduction

deduction = (price/100) * vat;

reductionVAT = (price - deduction);

// Is VAT and/or a discount required?

var answer = confirm ("VAT required?")
if (answer)
{
alert ("Price = " + price + ", VAT = " + deduction + ", New Price is: " + reductionVAT)
var answer = confirm ("Discount Required?")
if (answer)
{
alert ("Price = " + reductionVAT + ", Discount = " + reduction + "New price is: " + priceDiscount)
else
alert ("No Discount Required. Price is: " + reductionVAT)
}
else
alert ("No VAT required.")
var answer = confirm ("Discount Required?")
{
if (answer)
alert ("Price = " + price + ", Discount = " + reduction + "New price is: " + priceNoVATDiscount)
else
alert ("No Discount Required. Price is: " + price)
}
}

</script>
</html>

I am having trouble getting this to work properly. What I am trying to do is come up with a simple vat deduction + student discount calculator. I cannot seem to get it working.

Philip M
Oct 11th, 2010, 02:13 PM
Have you tried your error console?

A number of errors in this section:

alert ("Price = " + price + ", VAT = " + deduction + ", New Price is: " + reductionVAT)
var answer = confirm ("Discount Required?")
if (answer)
{
alert ("Price = " + reductionVAT + ", Discount = " + reduction + "New price is: " + priceDiscount)
else
alert ("No Discount Required. Price is: " + reductionVAT)
}
else
alert ("No VAT required.")

It comes from the bad habits of not using braces at all if the conditional statement is only one line, e.g.
else
alert ("No VAT required.")
and the equally bad habit of placing the opening brace on the next line
if (answer)
{
rather than the same line.
if (answer) {
Take it from me, both of these habits will cause you grief at some stage.

I am not sure what your VAT calculation is supposed to do. What does "No VAT required" mean?


"When two trains approach each other at a crossing, both shall come to a full stop and neither shall start up again until the other has gone." - Kansas State Legislature, early 1890's

levi15791
Oct 11th, 2010, 02:15 PM
sorry I am new to Javascript so bear with me :D

The no VAT required is just stating that no VAT reduction required.


var answer = confirm ("VAT discount required?");
if (answer)
alert ("Price = " + price + ", VAT = " + deduction + ", New Price is: " + reductionVAT);
var answer = confirm ("Discount Required?");
if (answer)
alert ("Price = " + reductionVAT + ", Discount = " + reduction + "New price is: " + priceDiscount);
else <--------------------------------------------------------------------------------------
alert ("No Discount Required. Price is: " + reductionVAT);
else
alert ("No VAT discount required.");
var answer = confirm ("Discount Required?");
if (answer)
alert ("Price = " + price + ", Discount = " + reduction + "New price is: " + priceNoVATDiscount);
else
alert ("No Discount Required. Price is: " + price);

error console states syntax error where the <--- is

Philip M
Oct 11th, 2010, 02:21 PM
error console states syntax error where the <--- is

Yep, see my remarks about the correct use of braces.

You cannot have two else statements following one if. answer is a boolean - either true or false.

It must be

if (answer) { // do something
}
else { // do something different
}

levi15791
Oct 11th, 2010, 02:24 PM
so how would I go about in correction this error as I need two conditions, one where the VAT discount is required and one where it isnt in order to then allow me to calculate student discount?

Philip M
Oct 11th, 2010, 02:28 PM
Take it in two bites. Calculate the price with VAT reduction (if any) and then calculate the price with student discount (if any) based on that. But I do not really understand why VAT should be deducted from the price - being a student does not exempt you from VAT.

This should give you a push forward:-


var price = parseFloat(prompt ("Enter Price", ""));
// note that you need to ensure that price is a number - use isNaN()
var exVATprice = price;
var VAT = .175; // note VAT expressed as a decimal
var answer = confirm ("Are you entitled to VAT discount");
if (answer) {
var exVATprice = price * (1-VAT);
}
// no need for an else statement as answer can only be true or false
alert (exVATprice);
Check out frorum Rule#1.5. We are very happy to assist and guide you, but we will not do your homework for you.

levi15791
Oct 11th, 2010, 02:31 PM
I know that the whole code doesnt seem realistic. Perhaps VAT could be staff discount instead? What I am trying to do is two prompts that pop up - one for initial discount and one for student discount. If no initial discount then use original price with student discount prompt else use initial discount price with student discount prompt.

levi15791
Oct 11th, 2010, 02:38 PM
I know that the whole code doesnt seem realistic. Perhaps VAT could be staff discount instead? What I am trying to do is two prompts that pop up - one for initial discount and one for student discount. If no initial discount then use original price with student discount prompt else use initial discount price with student discount prompt.

This is not homework, this is just extra curricular stuff I am trying to do off my own back. Like an expansion of the stuff we have done in lectures

barkermn01
Oct 11th, 2010, 02:40 PM
Curly Tags for if's more than one line you work is looking very VB lol,


if (answer){

}else{

}

This opens and closes your if's you have to do this if your if has more than one line of code


if(answer)
alert("hello");
else
alert("bye");

Would work but the moment you add more that one line to a statment you need to use {}

I tend to use {} as a best practise as they dont stop it working if there is only one line

Just as Philip M said, i just though i would explain a little more

Philip M
Oct 11th, 2010, 02:50 PM
This is not homework, this is just extra curricular stuff I am trying to do off my own back. Like an expansion of the stuff we have done in lectures

Follow the guidance you were given in Post#6. Then continue to calculate the student discount (if any) in exactly the same way. Note that the discount should be expressed as .1, not 10.

Once more - it is bad practice to omit braces (even where strictly they are not required) and/or to place the opening brace on the following line.

levi15791
Oct 11th, 2010, 02:56 PM
will get back to you after trying your advice, thank you :D

Philip M
Oct 11th, 2010, 03:12 PM
We both made the classic error in calculating the ex-VAT price. :o
17.5% is the VAT rate to be applied to the pre-tax price to arrive at the final shop price. To reduce the VAT-inclusive price to the pre-VAT price then the formula is of course different.

The code should read:-



var exVATprice = price;
var VAT = .175; // note VAT 17.5% expressed as a decimal
var answer = confirm ("Are you entitled to VAT discount?");
if (answer) {
var exVATprice = price / (1+VAT);
}

If the VAT-inclusive price is 100 the pre-VAT price is 85.1063829787234 (not 82.5!)

Expressed differently, the VAT fraction for the 17.5% rate is 7/47 (or 40/47 to calculate the pre-VAT price).

levi15791
Oct 12th, 2010, 01:12 AM
still not getting anywhere :(

Philip M
Oct 12th, 2010, 09:05 AM
still not getting anywhere :(

Really? What do you expect us to do if you do not post the code you are having difficulty with?

Look at Post#6 again (modified as per Post#12).

Why can you not implement this?

levi15791
Oct 13th, 2010, 01:50 PM
I have not met parseFloat yet. I will endeavor to look it up and research it for my own educational purposes.

Philip M
Oct 13th, 2010, 02:11 PM
Data entered into a textbox is always a string value. If the value is to be interpreted as a number it must be explicitly converted to a number, although sometimes (depending on how the value is processed later on) the conversion will be automatic. There are several ways to do this - parseInt(), parseFloat(), Number(), value*1, +value.

If an arithmetic operation such as * or / is performed on the value, it will be automatically converted into a number. One exception - the + sign will be considered to be string concatenation, not arithmetic addition, unless the value is explicitly converted to a number. So 2+2 returns 22 (a string, not a number) if concatenated, but (number) 4 if subject to arithmetic addition.

A string value such as abc multiplied or divided by a number does not make sense, so the returned value is NaN (not a number). But two string values abc and 123 can be concatenated with a + sign into abc123.

For more info see:-
http://www.w3schools.com/jsref/jsref_parsefloat.asp

levi15791
Oct 14th, 2010, 12:34 PM
<html>
<script>
// Author: L Freeman
// Date: 11/10/10
// Purpose: Calculate student discount/vat reductions

var price = parseFloat(prompt ("Enter Price ()", ""));
var discount = 0;
var exVATprice = price;
var vat = .175;
var total = 0;
var reduction = 0;

var answer = confirm ("Are you entitled to VAT discount?");
if (answer) {
var exVATprice = (price - (price*vat));
var answer = confirm ("Are you entitled to a discount?");
if (answer) {
discount = parseFloat(prompt ("Enter Discount (%)", ""));
reduction = exVATprice * (discount/100);
total = (exVATprice - reduction);
alert("Your final price is " + total);
}
else
alert("Your final price is " + exVATprice);
}
var answer = confirm ("Are you entitled to a discount?");
if (answer) {
discount = parseFloat(prompt ("Enter Discount (%)", ""));
reduction = exVATprice * (discount/100);
total = (exVATprice - reduction);
alert("Your final price is " + total);
}
else
alert("Your final price is " + exVATprice);
}

</script>
</html>


This is what I have so far, it is working fine, all I need to do now is to get a discount prompt box for when a VAT discount is not required. Any help with this as I cannot workout the best methodology for this?

levi15791
Oct 14th, 2010, 12:44 PM
<html>
<script>
// Author: L Freeman
// Date: 11/10/10
// Purpose: Calculate student discount/vat reductions

// Declare Variables
var price = parseFloat(prompt ("Enter Price ()", ""));
var discount = 0;
var exVATprice = price;
var vat = .175;
var total = 0;
var reduction = 0;

// See if they are entitled to a VAT exemption
var answer = confirm ("Are you exempt from VAT?");
if (answer) {
// work out the price if they are exmpt from VAT
var exVATprice = (price - (price*vat));
// See if they are entitled to a further discount after VAT reductions
var answer = confirm ("Are you entitled to a discount?");
if (answer) {
// Ask for discount percentage
discount = parseFloat(prompt ("Enter Discount (%)", ""));
// Work out the reduction
reduction = exVATprice * (discount/100);
// work out new price
total = (exVATprice - reduction);
// display new price
alert("Your final price is " + total);
}
// if not exempt from tax
else
// display price if no discount but VAT reduction
alert("Your final price is " + exVATprice);
}
// see if the price with VAT require a discount
var answer = confirm ("Are you entitled to a discount?");
if (answer) {
// calculate discount
discount = parseFloat(prompt ("Enter Discount (%)", ""));
// calculate reduction
reduction = price * (discount/100);
// calculate total price with VAT and discount
total = (price - reduction);
// display price with VAT and discount
alert("Your final price is " + total);
}
else
// display price with VAT but without a discount
alert("Your final price is " + price);

</script>
</html>


after a bit of fiddling around with the code I finally have it working :D

levi15791
Oct 14th, 2010, 10:55 PM
<html>
<script>
// Author: L Freeman
// Date: 11/10/10
// Purpose: Calculate student discount/vat reductions

// Declare Variables
var price = parseFloat(prompt ("Enter Price ()", ""));
var discount = 0;
var exVATprice = price;
var vat = .175;
var total = 0;
var reduction = 0;

// See if they are entitled to a VAT exemption
var answer = confirm ("Are you exempt from VAT?");
if (answer) {
// work out the price if they are exmpt from VAT
var exVATprice = (price - (price*vat));
// See if they are entitled to a further discount after VAT reductions
var answer = confirm ("Are you entitled to a discount?");
if (answer) {
// Ask for discount percentage
discount = parseFloat(prompt ("Enter Discount (%)", ""));
// Work out the reduction
reduction = exVATprice * (discount/100);
// work out new price
total = (exVATprice - reduction);
// display new price
alert("Your final price is " + total);
}
// if not exempt from tax
else
// display price if no discount but VAT reduction
alert("Your final price is " + exVATprice);
}
// see if the price with VAT require a discount
var answer = confirm ("Are you entitled to a discount?");
if (answer) {
// calculate discount
discount = parseFloat(prompt ("Enter Discount (%)", ""));
// calculate reduction
reduction = price * (discount/100);
// calculate total price with VAT and discount
total = (price - reduction);
// display price with VAT and discount
alert("Your final price is " + total);
}
else
// display price with VAT but without a discount
alert("Your final price is " + price);

</script>
</html>


after a bit of fiddling around with the code I finally have it working :D

only error I find is if I do a VAT exemption, after the discount bit it will go to the part where the person is not exempt from VAT. I need help to get the code to end when a discount has been found. What I am thing is an OR option.

Old Pedant
Oct 14th, 2010, 11:47 PM
I know we aren't supposed to *DO* homework for people, but this thread has just gotten too painful to read.

The code is just *WAY* overly complex.

My version:

<html>
<body>
<script type="text/javascript">
var vat = 0; // percent
var discount = 0; // percent
var price = NaN; // NaN to begin, will be pounds


while ( isNaN(price) ) {
price = parseFloat(prompt ("Enter Price ()", ""));
}
if ( confirm("Are you exempt from VAT?") )
{
vat = 17.5; // percent
}
if ( confirm("Are you entitled to a discount?") ) {
discount = NaN;
while ( isNaN(discount) ) {
discount = parseFloat(prompt("Enter your discount (%)", ""));
}
}
// now calculate and create message:
var msg = "Base price: " + price.toFixed(2);

if ( vat != 0 ) {
price = price / ( 1 + vat/100 ); // phillip's calculation...surely more accurate
msg += "\nVAT exemption of " + vat + "%"
+ "\nex-VAT price: " + price.toFixed(2);
}

if ( discount != 0 ) {
price = price * ( 1 - discount/100 );
msg += "\nDiscount of " + discount + "%";
}
msg += "\n\nFinal price: " + price.toFixed(2);
alert(msg);
</script>
</body>
</html>

levi15791
Oct 15th, 2010, 12:07 AM
As I said earlier in the thread and I will reiterate now, this IS NOT homework. It is in my own time, with my own effort. Also you do not get 'homework' at university. I am just doing this to further my understanding of basic javascript. Thanks for the help though. I will read through your code and break it down into its basics so I get an idea of it.

Old Pedant
Oct 15th, 2010, 03:02 AM
Sorry, I didn't read the entire thread. It just felt like homework.

Okay to explain:

Instead of trying to get the discount two different places, once where there is VAT exemption and once where there is not, just do it one place! As you can see there.

Also, notice how I validated the data inputs: The price and the discount. I stay in a loop on each until the user enters a value that parseFloat accepts. NaN is a constant built into JavaScript that indicates that a given number is "Not A Number". And correspondingly, the isNaN( ) builtin function tests for that value. If you try to do

var n = parseFloat("whatever");
then indeed parseFloat *will* give you a value of NaN. Very handy.

Notice how I have separated the data entry from the calculations. This is on purpose. Later on, you will not use the very very primitive functions Confirm() and Prompt() to interact with people. You will use a <form>. And then the very nature of a <form> will force this kind of coding.

Hope this does get you off on a better foot.

Philip M
Oct 15th, 2010, 02:28 PM
Old Pedant -

Part of the difficulty here is the silliness of the contrived question. Noone - no person, no company - (except a foriegn or export customer) is "exempt" from paying UK VAT, and no-one (not even a student) can somehow to buy something without paying the appropriate VAT. Presumably the same applies to Sales Tax in the USA. A foreign visitor must pay VAT, but may obtain a refund when they leave the country (export the goods)

In the context of UK VAT, the word "exempt" has a special technical meaning. Some goods and services are exempt from VAT, such as insurance and finance, education and training, medical services, funerals and charitable fund-raising events. So the transaction does not attract VAT payable by the final customer - but the supplier is not able to recover any VAT paid on its inputs. Example:- postal services are exempt from VAT but the Post Office is unable to reclaim the VAT content of its inputs, such as VAT on mail sacks, bicycles, vehicle fuel or repairs. So those costs are passed on in the selling price to customers. They are not recoverable by the customer - whether a person or a business. So what is supposed to be "exempt" is in fact taxable but one step up the chain from the final customer. "Exempt" means exempt from tax only on the final mark-up in the supply chain - not on the total end-user price.

Old Pedant
Oct 15th, 2010, 08:43 PM
It's completely off-topic, but...

No, in the USA, under most circumstances only the final retail purchaser pays the sales tax. Although the details of that rule vary some from state-to-state (and some states don't even have sales tax! Oregon, for example).

Example: When we had our own company and we ordered diskettes (which we then labelled and wrote our software onto), we didn't pay sales tax on them. And when we sold them to a wholesaler or retaiiler, *they* didn't pay sales tax. Heck, even if we sold them to an out-of-state customer and shipped them, the customer didn't pay sales tax. Only customers from our own state who purchased directly from us paid the sales tax to us. Presumably, customers who bought from stores in other states paid that state's sales tax. (Note that most US states are now banding together to get this changed, so that mail order customers *will* pay sales tax. It's been a big revenue hole that has gotten much bigger since the advent of the internet, of course.)