JavaScript Assignment - Conditionals (IF/Else Statements) - javascript

The basis of the assignment is to use the if/else if statements to set up the script. I need a little help finishing up the if/else part and for someone to look over any errors. Here's the assignment:
Write the JavaScript code in one HTML document using IF, and IF/Else statements for the following three situations. For each one make sure to write comments for each section.
Determine tax rate based on income and what the tax would be on the income.
Variable declarations section
1. Declare a variable that holds the income amount entered by the user.
2. Declare a variable that holds the minimum income that will not be charged taxes.
3. Declare a variable that holds the tax percentage for tax bracket 1.
4. Declare a variable that holds the tax percentage for tax bracket 2.
5. Declare a variable that holds the highest income for tax bracket 1.
6. Declare a variable that holds the highest income for tax bracket 2.
Assignments section
7. Assign $1500 as the highest income amount that will not be charged taxes.
8. Assign the highest income for tax bracket 1 to be $25K and the tax percent to 15%. Anything over $25K is in the next tax bracket.
9. Assign the highest income for tax bracket 2 to be $40K and the tax percent to 20%. Anything over $40K is in the next tax bracket.
10. Ask the user to enter a dollar amount.
11. Convert the data entered into a number.
Logic and Output section
12. Use only variables in your logic.
13. Determine whether or not the dollar amount entered is taxable.
14. Determine whether or not the dollar amount is in tax bracket 1 or 2.
15. Calculate the amount of tax on the dollar amount and display a message that tells the user what the tax amount would be on the number they entered.
16. For amounts greater than $40k display the message “I do not have the data to calculate the tax on this income.
Testing: Try values that are equal to the highest income for each bracket and the highest income for no taxes. Try numbers greater than the 40,000. Try amounts like 25,001 or 40,001.
My code thus far:
<script type="text/javascript">
// variable declarations
var userIncome;
var minIncomeNoTax;
var taxPercentBrack1;
var taxPercentBrack2;
var hiIncomeBrack1;
var hiIncomeBrack2;
var currentTaxBracket;
// Assignments
userIncome = prompt("Please enter your income in dollar amount.","");
minIncomeNoTax = 1500;
taxPercentBrack1 = 15/100;
taxPercentBrack2 = 20/100;
hiIncomeBrack1 = 25000;
hiIncomeBrack2 = 40000;
// Calculations & Output
if (userIncome >=minIncomeNoTax && userIncome <=hiIncomeBrack2)
{
alert("Your income is taxable.");
}
else if (userIncome >=minIncomeNoTax && userIncome <=hiIncomeBrack1)
{
alert("Your income amount is in tax bracket 1.");
}
else if (userIncome >hiIncomeBrack1 && userIncome <=hiIncomeBrack2)
{
alert("Your income amount is in tax bracket 2.");
}
else
{
alert("Sorry, I do not have the data to calculate the tax on this income.");
}
// output
document.write("Your Income: $" +userIncome + "<br />");
</script>

I fixed your if/else statement, and it seems to work now. I put it on jsfiddle:
http://jsfiddle.net/gXQXG/13/
Your issue was
if (userIncome <=1500 && userIncome >=40000)
else if (userIncome <=1500 && userIncome >=25000)
else if (userIncome <=25001 && userIncome >=40000)
The second statement in all three should be <=
A number cannot be both less than 1500 and greater than 4000 ;)
Next Step
You should replace the constants 1500, 25000, and 40000 with the variables you declared, hiIncomeBrack1 and hiIncomeBrack2
Lastly, there is one more issue in your logic, but, I will let you find that one. It has to do with two of the <= needing to actually be a <
Updated Code
// variable declarations
var userIncome;
var minIncomeNoTax;
var taxPercentBrack1;
var taxPercentBrack2;
var hiIncomeBrack1;
var hiIncomeBrack2;
var currentTaxBracket;
var totalTaxDue;
// Assignments
userIncome = prompt("Please enter your income in dollar amount.", 0);
minIncomeNoTax = 1500;
taxPercentBrack1 = 15 / 100;
taxPercentBrack2 = 20 / 100;
hiIncomeBrack1 = 25000;
hiIncomeBrack2 = 40000;
// Calculations & Output
if (userIncome >= minIncomeNoTax && userIncome <= hiIncomeBrack2)
{ //The user's income falls within our range of knowledge.
alert("Your income is taxable.");
if (userIncome >= minIncomeNoTax && userIncome < hiIncomeBrack1)
{ //The user falls into our first bracket
alert("Your income amount is in tax bracket 1.");
currentTaxBracket = taxPercentBrack1;
}
else if (userIncome >= hiIncomeBrack1 && userIncome <= hiIncomeBrack2)
{ //The user falls into our second bracket
alert("Your income amount is in tax bracket 2.");
currentTaxBracket = taxPercentBrack2;
}
}
else
{ //Can't help this user, they are not within our limits.
alert("Sorry, I do not have the data to calculate the tax on this income.");
}
//Figure out the actual amount due
//Need to use parseInt to convert from string to int.(User types a string into the prompt.)
totalTaxDue = currentTaxBracket * parseInt(userIncome);
// output
document.write("Your Income: $" + userIncome + "<br />");
//Multiply the decimal tax rate by 100 so we can print out a nice and clean %.
document.write("Your Tax Percent: " + (currentTaxBracket * 100) + "%<br />");
document.write("Pay Uncle Sam: $" + totalTaxDue + "<br />");

Related

Get subtotal, apply discount, and show new amount

I have the code below but I'm having issues when the dollar amount has commas, for example $1,234.56. When I use the code below, it spits out 0.00. It should show the new subtotal with comma(s) if it's over a thousand.
var subtotal = $('.divWithAmount').text().replace("$",""); // Get the subtotal amount and remove the dollar sign
var discount = subtotal * 0.2; // Multiply the amount by 20%
var newSub = subtotal - discount; // Calculate the new subtotal
var newSubtotal = newSub.toFixed(2); // Show only the last two numbers after the decimal
console.log(newSubtotal);
Thanks for your help!
The main reason it doesn't work is that the returned value from $('.divWithAmount').text() is of type String
To do operations it needs to be a number, and to enable that you also need to remove the comma and then parse it with e.g. parseFloat().
var subtotal = parseFloat($('div').text().replace("$","").replace(",",""));
var discount = subtotal * 0.2; // Multiply the amount by 20%
var newSub = subtotal - discount; // Calculate the new subtotal
var newSubtotal = newSub.toFixed(2); // Show only the last two numbers after the decimal
console.log(parseFloat(newSubtotal).toLocaleString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>$51,234.56</div>
As commented, I updated my answer with toLocaleString, so the comma gets added back.
Here is a couple of ways how to localize the end result:
- Javascript Thousand Separator / string format
- Add thousands separator to auto sum
- convert a JavaScript string variable to decimal/money
to get number out of string value just do like this
var amount = "$1,234.56";
var doublenumber = Number(amount.replace(/[^0-9\.]+/g,""));
once you get number then you can perform operation you want and it will resolve your issue that you are facing.

having trouble with doing math with text box value and a calculated value

I am using a function in my code that takes and does math with a value from a text box that the user writes in and also a calculated value that is used earlier in the page. If the text box value is not a positive number an alert will appear showing that the value must be a positive number. If it is a positive number, it shows an alert with the outcome of the math. The only problem is, when this happens, what appears is where the number should be there is instead "NaN". I believe this is because the values I'm using aren't actually numbers but I'm not sure how to fix this.
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = (total / 1000) * 0.621371;
document.getElementById('total').innerHTML = total;
}
function calc_gallons() {
var total = parseInt(document.getElementById("total").value)
var averagempg = parseInt(document.getElementById("averagempg").value);
var gallons = 0;
if (averagempg > 0) {
gallons = total / averagempg
window.alert("This trip requires " + gallons + " gallon(s). Have safe travels!");
}else {
window.alert("Your average MPG must be a positive number in order to calculate the gallons required for this trip.");
}
}
#this is the text box and the button that does the function
<p>Your Average MPG:<input type="text" id="averagempg" name="MPG"></p>
<button type="button" name="Calculate" onclick="calc_gallons()">Calculate!
Better use explicit type conversion:
var total = Number(document.getElementById("total").value);
var averagempg = Number(document.getElementById("averagempg").value);
parseInt then called on empty string ('') returns NaN.
If the first character cannot be converted to a number, parseInt
returns NaN.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
Examples: https://coderwall.com/p/kwhkig/javascript-number-conversion
The problem is getting total inside calc_gallons(). You're trying to get it from value, but you have it in a span. So either put total in a disabled input, or get it via innerHTML:
var total = parseInt(document.getElementById("total").innerHTML);
Are you sure you used the console? I failed to see the issue at first, and the following revealed that total is NaN:
console.log("total:", total, typeof total);
console.log("averagempg:", averagempg, typeof averagempg);

Search a range in parse javascript

I have a Class that help me to keep a range of values, it consist in 3 columns named min, max and price. When the user give me a number (example quantity=5) I need to search all the prices that the quantity satisfy this rule:
quantity=5 min >= quantity AND max <= quantity
var quantity = Number(req.body.quantity);
var Range = Parse.Object.extend("PriceRange");
var query = new Parse.Query(Range);
query.limit(1000);
query.greaterThanOrEqualTo("min",quantity);
query.lessThanOrEqualTo("max",quantity);
When I make this the result is always 0 and I have a row that is min = 1, max = 10 and price = 10
What is wrong? Parse don´t let me do querys like that?
It looks like the inequalities are reversed.
query.greaterThanOrEqualTo("min",quantity); // means: min >= quantity
query.lessThanOrEqualTo("max",quantity); // means: max <= quantity
...constrains the query to find objects where the value of min is greater than quantity, and likewise for the other constraint.
Those two constraints together present an impossible condition: where some number is both smaller than some small number and larger than some large number. Fix by reversing...
query.lessThanOrEqualTo("min",quantity); // where min <= quantity
query.greaterThanOrEqualTo("max",quantity); // where max >= quantity

Car loan calculator in Javascript displays nothing

I hope someone can help with this:
I am currently working on a motor dealership website. On this website is a car loan calculator that calculates your monthly repayments. I have successfully created a basic calculator that calculates the correct amount.
The client isn't happy with that. They want a more advanced calculator that calculates the monthly repayments with balloon considerations and a deposit and initiation and admin fees.
I altered the code to reflect that, but now the thing won't work anymore. I can't find any error in my code.
Here's the Javascript that's supposed to do the calculation:
function calculate() {
// Get the user's input from the form. Assume it is all valid.
// Convert interest from a percentage to a decimal, and convert from
// an annual rate to a monthly rate. Convert payment period in years
// to the number of monthly payments.
var principal = document.loandata.principal.value;
var lessDeposit = document.loandata.deposit.value;
var adminFee = document.loandata.admin.value;
var initiationFee = document.loandata.initiation.value;
var interest = document.loandata.interest.value / 100 / 12;
var payments = document.loandata.years.value * 12;
var balloonPercent = document.loandata.balloon.value / 100;
// Now compute the monthly payment figure, using esoteric math.
var balloonFinal = (principal * balloonPercent);
var totalPrincipal = (principal + initiationFee + balloonfinal - lessDeposit);
var x = Math.pow(1 + interest, payments);
var monthly = (totalPrincipal*x*interest)/(x-1);
// Check that the result is a finite number. If so, display the results
if (!isNaN(monthly) &&
(monthly != Number.POSITIVE_INFINITY) &&
(monthly != Number.NEGATIVE_INFINITY)) {
document.loandata.payment.value = round(monthly + adminFee);
document.loandata.total.value = round(monthly * payments);
document.loandata.totalinterest.value =
round((monthly * payments) - principal);
}
// Otherwise, the user's input was probably invalid, so don't
// display anything.
else {
document.loandata.payment.value = "";
document.loandata.total.value = "";
document.loandata.totalinterest.value = "";
}
}
// This simple method rounds a number to two decimal places.
function round(x) {
return Math.round(x*100)/100;
}
Also, if possible, there needs to be some validation. Like purchase price, interest rate and payment period are required fields. But the rest are not. So if someone fills in the required fields but not the rest, the calculator still needs to work, but if someone does NOT complete one of the required fields, they need to be prompted to do so.
For those who don't know what a balloon payment is, here's an example;
Purchase Price is R117 000
You decide on a balloon payment of 30%. On the initial purchase price, the 30% amounts to R35 100. This amount is then subtracted from your initial purchase price so that means your purchase is now R81 900. After that comes the deposit, which is subtracted, and the extras and the admin and initiation fees. So the monthly repayments are calculated using this new purchase price of R81 900 + extras - deposit (if any). For interest sake, after your contract ends, you have to pay the balloon amount in full or re-finance the vehicle.
PS: I'm a complete newbie when it comes to JavaScript. So any help would be greatly appreciated.
If the result is nothing, one of these three conditions is likely triggering the else statement:
if (!isNaN(monthly) &&
(monthly != Number.POSITIVE_INFINITY) &&
(monthly != Number.NEGATIVE_INFINITY)) {
You have a typo in the JS, you need to change balloonfinal to be balloonFinal with a capital F in the var totalPrincipal = line of code.
The principal, lessDeposit, adminFee, initiationFee may also need to be typecast as an integer/float.

Error in if statement for setting balance

Am getting an if statement error, but can't figure it out. Can you tell me what's wrong?
var balance = 20.97;
if (balance < 10.00 ) {
// console.log() the balance minus 5 dollars
console.log("Your balance is (balance - 5.00).");
} else {
// Just console.log() the balance
console.log("Your balance is (balance).");
}
You're just printing a string. Placeholdering works like this:
console.log('Your balance is %s.', balance - 5.0);
console.log("Your balance is (balance - 5.00).");
should be
console.log("Your balance is %s.", (balance - 5.00));
The former will just say "Your balance is (balance - 5.00)" because JavaScript does not treat words like "balance" as variable references when they appear inside a string literal.
In the second, the message format string is distinct from the expression you want to display, and console.log replaces %s sequences with the other arguments.

Categories

Resources