javascript passing functions nan and undefined errors - javascript

This works tell I hit the tax function. Then I start getting
nan and undefined errors. Cant figure out why the tax function is not picking up the code from the other functions.
/ Saturday May 27 2017
{
// Global variables
var orderCount = 0;
var takeOrder = function (topping, crustType) {
// add one to order count
orderCount = orderCount + 1
return('Order: ' + crustType + ' pizza topped with ' + topping );
}
var getSubTotal = function(itemCount){
var subTatal = (itemCount * 7.5);
return (subTatal + ' subtotal of ' + ' itemCount ' + (itemCount));
}
var getTax = function (){
var subTatal = subTatal * 0.06;
// getTheTax = (subTatal * 0.06)
return subTatal + ' with tax of ' + (subTatal)
}
var getTotal = function (){
var myTotal = getSubTotal + getTax;
return ' tax ' + getTax + 'plus subtotal ' + getSubTotal() + ' is ' + (myTotal);
}
console.log(takeOrder('bacon', 'thin crust'));
console.log(takeOrder('cheese', 'thick crust'));
console.log(takeOrder('pepperoni', 'medium crust'));
console.log(getSubTotal(10));
console.log(' getTax ' + getTax());
console.log(getTotal());
}

This is the corrected version of your code.
var takeOrder = function(topping, crustType) {
console.log('Order: ' + crustType + ' pizza topped with ' + topping);
return 1;
}
var getSubTotal = function(orderCount) {
var subTotal = (orderCount * 7.5);
console.log('Subtotal of ' + subTotal.toFixed(2) + ' with item count ' + orderCount);
return subTotal;
}
var getTax = function(subTotal) {
var tax = subTotal * 0.06;
console.log('Tax is ' + tax.toFixed(2));
return tax;
}
var getTotal = function(subTotal, tax) {
var total = subTotal + tax;
console.log('Total is ' + total.toFixed(2));
return total;
}
var orderCount = 0;
orderCount += takeOrder(orderCount, 'bacon', 'thin crust');
orderCount += takeOrder('cheese', 'thick crust');
orderCount += takeOrder('pepperoni', 'medium crust');
var subTotal = getSubTotal(orderCount);
var tax = getTax(subTotal);
var total = getTotal(subTotal, tax);
Summary of corrections
Made functions return Number rather than String
Now all functions are almost pure functions (don't cause side-effects other than logging)
Formatted numbers prior to printing them by rounding them to the second decimal
Fixed typographic errors (tatal rather than total).
Added parenthesis to function invocations (e.g: getTax() rather than getTax
Removed redundant invocations
More

you are defining a variable, and assigning into it it's value times something.
var subTatal = subTatal * 0.06;
In this case, subTatal does not have a value.
I think you should read about variables and scopes.
Read the link below:
https://www.w3schools.com/js/js_scope.asp

Your both function is returning the string :
....
return subTatal + ' with tax of ' + (subTatal)
...
return ' tax ' + getTax + 'plus subtotal ' + getSubTotal() + ' is ' + (myTotal);
You can go through this blog for converting strings to number:
https://coderwall.com/p/5tlhmw/converting-strings-to-number-in-javascript-pitfalls
Please make sure the what is the type of value you want to be returned form the function to use it.

var subTatal = subTatal * 0.06;
is equivalent of
var subTatal = undefined;
subTatal = subTatal * 0.06;
note, this subTatal is not the same as the one defined outside the function (learn scope)

If you create a variable inside a function it will exists only inside that function, so if you call that variable from inside another it will be undefined.
There are two ways:
declare these variables as global at the top of your code just like orderCount
functions can have inputs and output, so you can pass to a function the variable you need and ask it to return the result, which can be saved into a variable and later used.
For example:
function getSubtotal(orderCount) {
var subtotal = //do something
return subtotal }
function getTax(subtotal) {
var tax = //calculate tax
return tax }
var subtotal = getSubtotal(orderCount)
var tax = getTax(subtotal)

Related

How to get a number to display in alert box rather than NAN

I am learning javascript and I made a simple program to convert feet to meters and lbs to kg and I want to display the output using alert boxes in the correct measurements
I checked the variables using typeof and its coming back number but the alert boxes are still saying NAN.
I am new to javascript and Im following along with a udemy course.
var kgMark = parseFloat(kgMark);
var meterMark = parseFloat(meterMark);
var bmiMark = parseFloat(bmiMark);
var feetMark = parseFloat(feetMark);
var lbsMark = parseFloat(lbsMark);
kgMark = lbsMark / 2.2046;
meterMark = feetMark / 3.2808;
bmiMark = kgMark / (meterMark * meterMark);
feetMark = prompt('How tall is mark in feet?');
lbsMark = prompt('How much does mark weigh in pounds?');
alert('Mark is ' + ' ' + kgMark + ' '+ 'kilograms');
alert('Mark is ' + ' ' + meterMark + ' ' + 'meters');
alert('Marks BMI is ' + ' ' + bmiMark);
I have tried it several different ways and I am truly stuck. I keep getting the NAN error in the alert box.
First take a value then perform every logic:
var feetMark = prompt('How tall is mark in feet?');
var lbsMark = prompt('How much does mark weigh in pounds?');
feetMark = parseFloat(feetMark);
lbsMark = parseFloat(lbsMark);
var kgMark = lbsMark / 2.2046;
var meterMark = feetMark / 3.2808;
var bmiMark = kgMark / (meterMark * meterMark);
alert('Mark is ' + ' ' + kgMark + ' '+ 'kilograms');
alert('Mark is ' + ' ' + meterMark + ' ' + 'meters');
alert('Marks BMI is ' + ' ' + bmiMark);
Changing the code to the following worked:
var feetMark = parseFloat(prompt('How tall is mark in feet?'));
var lbsMark = parseFloat(prompt('How much does mark weigh in pounds?'));
kgMark = parseFloat(lbsMark / 2.2046);
meterMark = parseFloat(feetMark / 3.2808);
var bmiMark = parseFloat(kgMark / (meterMark * meterMark));
console.log('Mark is ' + ' ' + kgMark + ' '+ 'kilograms');
console.log('Mark is ' + ' ' + meterMark + ' ' + 'meters');
console.log('Marks BMI is ' + ' ' + bmiMark)
Whats happening in the code you posted is a mixture of something called hoisting and the fact that when you run parseFloat on an undefined variable, its making those variables NaN; which whatever operation you do on it will always remember NaN.
So, I would suggest to parseFloat the variables when you are sure that you receive some value in it.
I hope this helps.

Breaking down a JavaScript code into functions

Newbie student coder,
Here and I am developing a program that can alert program that once you type in the amount of money you give it will calculate the tip, and tax to get the total amount that the user owns. I have the base code down and divided it up into functions but when I put in a number it shows as unidentified.
Here is my code:
const TAXRATE=.095
const TIPRATE=.2
function foodCharge (foodCharge) {
return parseFloat(prompt("please enter the amount"));
}
foodCharge ();
function taxAmount (foodCharge,TAXRATE) {
return parseFloat(foodCharge*TAXRATE);
}
taxAmount();
function subAmount (foodCharge,taxAmount) {
return parseFloat(foodCharge+taxAmount);
}
subAmount ();
function tipAmount (TAXRATE,subAmount) {
return parseFloat (TAXRATE*subAmount);
}
tipAmount ();
function grandTotal (foodCharge, taxAmount, tipAmount) {
return grandTotal=parseFloat(foodCharge+taxAmount+tipAmount)
}
grandTotal ();
function finalCost(foodCharge,taxAmount, tipAmount, grandTotal ) {
alert ("Meal cost: "+ foodCharge + " \nTax: " + taxAmount + " \nTip: " +
tipAmount +" \nGrand total: " + grandTotal);
}
finalCost();
You need parseFloat function only when you parse float number from string. You don't need to parse result of regular math operation(if both numbers are not strings). When you pass function as a parameter to alert() you must pas it with brackets (), otherwise you pass the reference to a function.
If i correctly understand your question, here is your program:
const TAXRATE=0.095
const TIPRATE=0.2
function foodCharge (foodCharge) {
return parseFloat(prompt("please enter the amount"));
}
var charge = foodCharge ();
function taxAmount (charge, rate) {
return charge*rate;
}
var tax = taxAmount(charge, TAXRATE);
function subAmount (charge,tax) {
return charge+tax;
}
var amount = subAmount (charge,tax);
function tipAmount (rate,amount) {
return rate*amount;
}
var tip = tipAmount(TAXRATE,amount);
function grandTotal () {
return charge+tax+tip;
}
function finalCost() {
alert ("Meal cost: "+ charge + " \nTax: " + tax + " \nTip: " + amount +" \nGrand total: " + grandTotal());
}
finalCost();
You can adjust the function to be called within finalCost. Note, parseFloat() is only necessary at foodCharge function
const TAXRATE = .095
const TIPRATE = .2
function foodCharge() {
return parseFloat(prompt("please enter the amount"));
}
function taxAmount(charge, tax) {
return charge * tax;
}
function subAmount(charge, tax) {
return charge + tax;
}
function tipAmount(tip, sub) {
return tip * sub;
}
function grandTotal(charge, tax, tip) {
return charge + tax + tip;
}
function finalCost() {
let _foodCharge = foodCharge();
let _taxAmount = taxAmount(_foodCharge, TAXRATE);
let _subAmount = subAmount(_foodCharge, _taxAmount);
let _tipAmount = tipAmount(TIPRATE, _subAmount);
let _grandTotal = grandTotal(_foodCharge, _taxAmount, _tipAmount);
alert("Meal cost: " + _foodCharge + " \nTax: " + _taxAmount + " \nTip: " +
_tipAmount + " \nGrand total: " + _grandTotal);
}
finalCost();

Round number to two decimals

I'm trying to use Math.round for the total to show only two decimals, but it doesn't work as intended. What am I doing wrong?
$(document).ready(function() {
var totalPrice = 0;
$('.food').click(function() {
var $frm = $(this).parent();
var toAdd = $frm.children(".productInput").val();
var addPrice = parseFloat($frm.children(".priceInput").val());
var addAmount = parseFloat($frm.children(".amountInput").val());
if ($('.priceInput').val() == '') {
alert('Price can not be left blank');
};
if ($('.amountInput').val() == '') {
alert('Amount can not be left blank');
} else {
var div = $("<div>");
div.append("<p class='amount'>" + addAmount + "</p>", "<p class='product'> " + toAdd + " </p>", "<p class='price'>" + addPrice + "</p>", "<p class='delete'>" + "X" + "</p>");
$frm.parent().children(".messages").append(div);
totalPrice += addAmount * addPrice;
$(".totalPrice").text("Total Price: $" + totalPrice);
}
console.log(addAmount);
console.log(addPrice);
});
$(document).on("click", ".delete", function() {
/* var subAmount = parseFloat($(this).siblings(".amount").text());
var subPrice = parseFloat($(this).siblings(".price").text());
totalPrice -= subAmount * subPrice;
$(".totalPrice").text("Total Price: $" + totalPrice);*/
$(this).closest("div").remove();
console.log(subPrice);
console.log(subAmount);
});
$(document).on("mouseover", ".delete", function() {
var hoverAmount = parseFloat($(this).siblings(".amount").text());
var hoverPrice = parseFloat($(this).siblings(".price").text());
totalPrice -= hoverAmount * hoverPrice;
Math.round(totalPrice * 100) / 100
$(".totalPrice").text("Total Price: $" + totalPrice);
$(this).closest("div").fadeTo("fast", 0.4);
});
$(document).on("mouseout", ".delete", function() {
var subAmount = parseFloat($(this).siblings(".amount").text());
var subPrice = parseFloat($(this).siblings(".price").text());
totalPrice += subAmount * subPrice;
Math.round(totalPrice * 100) / 100
$(".totalPrice").text("Total Price: $" + totalPrice);
$(this).closest("div").fadeTo("fast", 1.0);
})
});
Since I'm using float, the numbers sometimes get changed into long decimals instead of the exact amount. I'm trying to prevent this by using Math.round. If anyone have another solution to the problem that would be appreciated too.
Use Number.prototype.toFixed() with 2 as argument, in order to round it to two decimals.
Just, remember that the returned value is a String:
let totalPrice = 4.655555;
totalPrice = totalPrice.toFixed(2);
console.log(totalPrice); // "4.66"
console.log(typeof totalPrice); // string
If you want to return a number, use Number(totalPrice.toFixed(2)) — just keep in mind that i.e: Number((7.005).toFixed(2)) will return 7 (without the decimal part)
If you work with currency it is better to use fixed point numbers for precision. There is no fixed-point number type in javascript, so consider using external libraries.
E.g. Big.js or bignumber.js

Javascript - passing returned variable to another function

I am trying to pass my results value from to projectYears() function to projectInvestment() function that will then write to the div tag. I am getting the error "result is not defined error". To me this makes sense. All the code is working as intended. Can someone please let me know how to achieve this.
function projectInvestment(nameId, investmentId, interestId, yearsId, amountId) {
var inputName = document.getElementById(nameId).value;
var inputInvestment = parseFloat(document.getElementById(investmentId).value);
var inputInterest = parseFloat(document.getElementById(interestId).value);
var inputYears = parseInt(document.getElementById(yearsId).value);
var inputAmount = parseFloat(document.getElementById(amountId).value);
projectYears(inputInvestment, inputInterest, inputYears);
var outputString = projectYears(result);
document.getElementById("outputDiv").innerHTML = outputString;
}
function projectYears(inInvest, inInterest, inYears) {
var interest = parseFloat(inInterest / 100);
var interestAmt = parseFloat(inInvest * interest);
var predictedInvest = parseFloat(inInvest + interestAmt);
var result = "<br /> Investment Schedule for <b>$" + inInvest.toFixed(2) +
" </b>at <b>" + inInterest + "% </b>annual interest for <b>" + inYears + "</b> years <br /><br />";
result += "<table border='1' align='center'><tr><th>Year</th><th>Amount</th>";
//for loop to loop through the years
for (var x = 1; x <= inYears; x++) {
result += "<tr><td>" + x + "</td><td>" + predictedInvest.toFixed(2) + "</td></tr>";
interestAmt = predictedInvest * interest;
predictedInvest = (predictedInvest + interestAmt);
}
result += "</table>";
return result;
//document.getElementById("outputDiv").innerHTML = result;
}
You are passing in a variable called result that isn't defined.
See this line in the projectInvestment function:
var outputString = projectYears(result);
It looks like, based on the function definition for projectYears, you should be passing in some of the variables you create above this line instead.
i.e.
var outputString = projectYears(inputInvestment, inputInterest, inputYears);
var inputAmount = parseFloat(document.getElementById(amountId).value);
var outputString = projectYears(inputInvestment, inputInterest, inputYears);
document.getElementById("outputDiv").innerHTML = outputString;

Adding numbers to running total in jquery loop

I have a variable that is supposed to hold a running total. On each pass of this loop, and amount should be added to the running total. I must be missing something, since I get either undefined or NaN.
$('#btnSubmit').click(function(e) {
var totalSqft;
$('.fieldset').each(function() {
var sqft;
var width = $(this).find('input:eq(0)').val();
var height = $(this).find('input:eq(1)').val();
var type = $(this).find('select').val();
if (type == 'tri') {
sqft = (width * height) / 2;
} else {
sqft = (width * height);
};
totalSqft += sqft;
alert('this ' + type + ' is ' + width + ' wide and ' + height + ' high, for a total of ' + sqft + ' square feet');
});
alert('Done. Total Sq Ft is ' + totalSqft);
})​
You need to initialize the value to 0:
var totalSqft = 0;
Otherwise, it gets initialized to undefined, and undefined + a number is NaN.

Categories

Resources