Tip Calculator results in NaN - javascript

I am a beginner, working on a beginner problem but need some help
I am trying to write my own tip calculator app but I result in NaN.
I am sure it is an easy fix but I don't see what the problem is yet. My code is below. Can someone tell me what I am doing wrong that results in my finalCost resulting in NaN instead of billAmount + tipTotal?
var billAmount = prompt('What is your total bill?');
var tipAmount = prompt('How much do you want to tip');
console.log(billAmount);
var tip = tipAmount / 100;
var tipTotal = tip * billAmount;
function finalCost(billAmount, tipTotal) {
return billAmount + tipTotal;
};
console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost());

So close! You just missed passing the values into your final calculation method.
var billAmount = prompt('What is your total bill?');
var tipAmount = prompt('How much do you want to tip');
console.log(billAmount);
var tip = tipAmount/100;
var tipTotal = tip*billAmount;
function finalCost(billAmount, tipTotal) {
return billAmount + tipTotal;
};
console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost(billAmount, tipTotal));
You could also remove the parameters and just use the "global" values in calculating
var billAmount = prompt('What is your total bill?');
var tipAmount = prompt('How much do you want to tip');
console.log(billAmount);
var tip = tipAmount/100;
var tipTotal = tip*billAmount;
function finalCost() {
return billAmount + tipTotal;
};
console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost());

There's another catch; setting float values directly from a prompt() doesn't ensure float values (treated as string by default), so wrap your prompt() functions in a parseFloat() function:
var billAmount = parseFloat(prompt('What is your total bill?'));
var tipAmount = parseFloat(prompt('How much do you want to tip'));
if(isNaN(billAmount) || isNaN(tipAmount)){
alert("Bill amount or Tip is Invalid");
} else {
console.log("This bill is " + billAmount);
var tip = tipAmount / 100;
var tipTotal = tip * billAmount;
console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost(billAmount, tipTotal));
}
function finalCost(billAmount, tipTotal) {
return billAmount + tipTotal;
};
This should validate that billAmount and tipAmount values are floats, and prevent further execution if they aren't.

Related

JS function formating currency

Good morning folks. I just started to learn JS and got a task in which I am stuck. I need to change number format to have 2 decimal places and it should also start with pound sign.
function formatCurrency() {
var formated = formated.toFixed(2);
return formated;
}
function calculateSalesTax(price: number) {
return price * 0.21;
}
const product = "You don't know JS";
const price = 19.99;
const salesTax = calculateSalesTax(price);
console.log("Product: " + product);
console.log("Price: " + formatCurrency(price));
console.log("Sales tax: " + formatCurrency(salesTax));
console.log("Total: " + formatCurrency(price + salesTax));
When I tried to shorten numbers it throws me an error.Could you please point me in correct direction, as it looks like a very simple task.
Try like this:
function formatCurrency(price) {
var formated = price.toFixed(2);
return formated;
}
function calculateSalesTax(price) {
return price * 0.21;
}
const product = "You don't know JS";
const price = 19.99;
const salesTax = calculateSalesTax(price);
console.log("Product: " + product);
console.log("Price: " + formatCurrency(price));
console.log("Sales tax: " + formatCurrency(salesTax));
console.log("Total: " + formatCurrency(price + salesTax));
The formatCurrency function needs to accept an argument (the price) passed into it and use that in the formatting.
The calculateSalesTax function shouldn't have the type definition added to the argument (this is fine in TypeScript).
Here is your correct code:
function formatCurrency(price) {
return `\u00A3 ${price.toFixed(2)}`;
}
function calculateSalesTax(price) {
return price * 0.21;
}
const product = "You don't know JS";
const price = 19.99;
const salesTax = calculateSalesTax(price);
console.log("Product: " + product);
console.log("Price: " + formatCurrency(price));
console.log("Sales tax: " + formatCurrency(salesTax));
console.log("Total: " + formatCurrency(price + salesTax));
You were not declaring an argument for formatCurrency. \u00A3 is the code for the pound sign, as putting £ will result in a bad behaviour in js. The backticks (``) allows you to use "literal", go search for it, it is a useful tool in javascript. Also, you attempted to declare a return type for calculateSalexTaxPrice, which you can not since typing is possibile in TypeScript only

Uncaught (in promise) TypeError: Cannot set property 'innerHTML' of null

I understand there are questions similar to this issue. And I have taken the time to look through them. But the implementation here is a little different than in some of the cases I looked at. The good news here is my fourth column, the running totals column, is correctly displaying the data I want. Everything is working (correctly calculated and displaying) so why is my app held up on this? I'd appreciate it. Thanks.
calculateRunningTotals(){
var attendantTotalCell = 0;
var total = 0;
var totalCell="";
var totalsCells = document.querySelectorAll("td:nth-child(3)");
totalsCells.forEach(function(cell, index){
console.log("The contents of the totals cell " + cell.innerText);
totalCell = cell.innerText;
attendantTotalCell = totalCell.replace(/[^0-9-.]/g, '');
total = parseInt(attendantTotalCell) + parseInt(total);
console.log("Attendant Total Cell is: " + attendantTotalCell);
console.log("Attendant Total is " + total);
cell.nextElementSibling.innerHTML = total;
})
}
If you add the following check to ensure that cell.nextElementSibling is defined, then this should resolve your problem:
calculateRunningTotals(){
var attendantTotalCell = 0;
var total = 0;
var totalCell="";
var totalsCells = document.querySelectorAll("td:nth-child(3)");
totalsCells.forEach(function(cell, index){
console.log("The contents of the totals cell " + cell.innerText);
totalCell = cell.innerText;
attendantTotalCell = totalCell.replace(/[^0-9-.]/g, '');
total = parseInt(attendantTotalCell) + parseInt(total);
console.log("Attendant Total Cell is: " + attendantTotalCell);
console.log("Attendant Total is " + total);
/* Add the following check to ensure nextElementSibling is defined
before attempting to access it */
if(cell.nextElementSibling) {
cell.nextElementSibling.innerHTML = total;
}
})
}

How to capitalize the first letter of a var in p5.js [duplicate]

This question already has answers here:
How do I make the first letter of a string uppercase in JavaScript?
(96 answers)
Closed 4 years ago.
I am building a weather forecast site using JavaScript's framework p5.js. I have a description about what's the weather like (ex. few clouds) but the problem is that the api I'm using has only lowercase description. I wan't them to be uppercase but i don't know how to capitalize them. Can somebody help me? (I tried many vanilla JavaScript methods)
var weather;
var apiPath = 'http://api.openweathermap.org/data/2.5/weather?q=';
var apiKey = '&appid=e0342ddf94a760131ffacfa0e12bddf4';
var unit = '&units=metric';
var input;
function setup() {
noCanvas(270,125);
var button = select('#submit');
button.mousePressed(weatherAskAndDraw);
input = select('#city');
}
function CapFirst(string)
{
return string.charAt(0).toUpperCase() + string.slice(1);
}
function keyDraw(){
if (weather){
var temp = weather.main.temp;
var humidity = weather.main.humidity;
var minTemp = weather.main.temp_min;
var maxTemp = weather.main.temp_max;
var country = weather.sys.country;
var city = weather.name;
var vis = weather.visibility;
var des = weather.weather[0].description;
var windSpeed = weather.wind.speed;
fill(255);
CapFirst(des);
document.getElementById("p1").innerHTML = "City: " + city;
document.getElementById("p2").innerHTML = "Description: " + des;
document.getElementById("p3").innerHTML = "Temperature: " + temp;
document.getElementById("p4").innerHTML = "Humidity: " + humidity;
document.getElementById("p5").innerHTML = "Wind Speed: " + windSpeed;
}
}
function weatherAskAndDraw(){
var url = apiPath + input.value() + apiKey + unit;
loadJSON(url, gotData);
keyDraw();
}
function gotData(data){
weather = data;
}
I have not worked with P5.js but as simple js
mode = "few clouds";
string = mode.charAt(0).toUpperCase() + mode.substr(1,mode.length).toLowerCase();
console.log(string);

Passing prompt values into functions triggered by "click" event on input buttons

I have a code which is intended to create 3 buttons (with JavaScript) and on each one of them I'm adding an event listener for click event. All of the buttons will execute the same function when it's clicked which is the mathProb() [I know it doesn't make much sense but I just want to experiment with things].
mathProb() function needs 3 arguments:
firstNumber which is the first operand.
secondNumber which is the second operand
operationSign which is the operation to be performed between the two operands
Here's the mathProb function (I put the function in the HTML head element):
function mathProb(firstNumber, secondNumber, operationSign){
switch(operationSign){
case "+":
var sum = (firstNumber + secondNumber).toFixed(2);
document.writeln("The sum of [" + firstNumber + " + " + secondNumber + "] is " + sum + " (adjusted to 2 decimal places)");
break;
case "-":
var subtract = (firstNumber - secondNumber).toFixed(2);
document.writeln("The subtraction of [" + firstNumber + " - " + secondNumber + "] is " + subtract + " (adjusted to 2 decimal places)");
break;
case "*":
var multiplication = (firstNumber * secondNumber).toFixed(2);
document.writeln("The multiplication of [" + firstNumber + " X " + secondNumber + "] is " + multiplication + " (adjusted to 2 decimal places)");
break;
case "/":
var division = (firstNumber / secondNumber).toFixed(2);
document.writeln("[" + firstNumber + " divided by " + secondNumber + "] is " + division + " (adjusted to 2 decimal places)");
break;
default:
document.writeln("You did not specify the operation sign, no operation could be performed between the two numbers!");
}
}
Now I'm planning to use the prompt() method to get the 3 arguments which will be used by the function, therefore the JavaScript code I put in the body element looks like this:
//create all the mathematical buttons
var addButton = document.createElement("input");
var subtractButton = document.createElement("input");
var multiplyButton = document.createElement("input");
var divideButton = document.createElement("input");
addButton.type = "button";
subtractButton.type = "button";
multiplyButton.type = "button";
divideButton.type = "button";
var firstNumber = parseFloat(prompt("Please enter the first number"));
var secondNumber = parseFloat(prompt("Please enter the second number"));
var operationSign = prompt("Please enter the operation sign you wish to perform on the two numbers");
//add a click event listener to all of the buttons
addButton.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
subtractButton.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
multiplyButton.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
divideButton.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
//add all the buttons to the body of the document
document.body.appendChild(addButton);
document.body.appendChild(subtractButton);
document.body.appendChild(multiplyButton);
document.body.appendChild(divideButton);
I realised that I haven't added any "value" to the buttons so I won't be able to differentiate them right now
My problem is that, once I run my code, I got the 3 prompts which will ask me for the firstNumber, the secondNumber, and the operationSign. However, for some reason, it seems like mathProb() function was executed 4 times Without ME CLICKING ON ANY OF THE BUTTONS
Here's what happened when I put 2 as the firstNumber, 3 as the secondNumber and + as operationSign:
http://imgur.com/a/APFbf
See what I'm saying? I have no idea what happened here and I can't seem to figure out what's wrong with the code either (I'm very inexperienced when it comes to javascript/html/css).
.addEventListener("click", mathProb(firstNumber,secondNumber,operationSign));
Should look like:
.addEventListener("click", function(evt) {
mathProb(firstNumber,secondNumber,operationSign);
});
If You want to deliver function to argument (without execution) use functionName without ().
Example:
var someFunctionWithFunctionInArgument = function(fun) {
fun(1);
};
var superFunction = function(num) {
alert(num);
};
someFunctionWithFunctionInArgument(superFunction); // alert 1
someFunctionWithFunctionInArgument(superFunction(2)); // alert 2 and error becouse fun is not a function now
You are going too complex.
You can have this simple solution
function operate(val1,op,val2){
switch(op){
case '+' : return val1+val2; break;
case '-' : return val1-val2; break;
case '*' : return val1*val2; break;
case '/' : return val1/val2; break;
default : return 0; break;
}
}
var start = document.createElement('button');
start.innerHTML="START";
start.addEventListener('click',function(){
var result=operate(parseInt(prompt("first val")),prompt("Operator"),parseInt(prompt("Second val")));
console.log(result);
});
document.body.appendChild(start);
<body></body>
Or even more simple
var button = document.createElement('button');
button.innerHTML="START";
button.addEventListener('click',function(){
var val1=parseInt(prompt("First Val"));
var op=prompt("Operator");
var val2=parseInt(prompt("Second Val"));
console.log(eval(val1+op+val2));
});
document.body.appendChild(button);
<body></body>
Even more simple
function start(){
console.log(eval(prompt("Enter expression : "))); // like 10+5
}
function startWithTest(){
var exp=prompt("Enter expression : ");
if(/^\d+[+-\/*]{1}\d+$/.test(exp)){
console.log(eval(exp));
}
}
<body><button onclick="start();">START</button> With validating : <button onclick="startWithTest();">START With Test</button></body>

Code won't run because I can't output more than one variable in document.write

My code won't run when I try to display more than one variable in the document.write section of the code. I'm pretty sure I was doing everything right.
<script type="text/javascript">
var name = prompt("Welcome to the Fruity Store. What is your name?","");
var product = prompt("What is the name of the product you would like?","");
var price = 1*prompt("How much does it cost?","");
var quantity = 1*prompt("How many of the fruit would you like?","");
var discount = 1*prompt("What was the discount of the product in decimal form?","");
var costoforder = (price*quantity);
var discounted = (price*quantity*discount);
var totalorder = (costoforder - discounted);
document.write("Thank you for placing an order with us " +name )
document.write("<p>The cost of buying " +quantity "of " +product "is " +costoforder </p>)
document.write("<p>The discount for this purchase is " +discounted </p>)
document.write("<p>With discount, your total order cost is " +totalorder</p>)
</script>
You are missing some plus signs in your string concatenation.
"<p>The cost of buying " + quantity + " of " + product + " is " + etc.
You are missing "+" signs after your variables.
You put
"String" + variable "string"
Instead of
"string" + variable + "string"
Several times in your document.write statements
You need to use the plus sign, +, for string concatenation. Also you are missing the ; after the statements.
<script type="text/javascript">
var name = prompt("Welcome to the Fruity Store. What is your name?","");
var product = prompt("What is the name of the product you would like?","");
var price = 1*prompt("How much does it cost?","");
var quantity = 1*prompt("How many of the fruit would you like?","");
var discount = 1*prompt("What was the discount of the product in decimal form?","");
var costoforder = (price*quantity);
var discounted = (price*quantity*discount);
var totalorder = (costoforder - discounted);
document.write("Thank you for placing an order with us " + name );
document.write("<p>The cost of buying " + quantity + "of " + product + "is " + costoforder + "</p>");
document.write("<p>The discount for this purchase is " + discounted + "</p>");
document.write("<p>With discount, your total order cost is " +totalorder + "</p>");
</script>

Categories