Values show together instead of as a new value - javascript

I did an exercise today in college, and it was a JavaScript program to calculate the average score of pupils in a test.
Here is my code:
<!DOCtype html>
<html>
<head>
<title>While loop</title>
</head>
<body>
<script>
//The total score of all pupils
var total = 0;
//The number of scores
var count = 1;
while (count <= 10) {
grade = prompt("Insert the grade:");
total = total + grade;
count++;
}
var average = +total / 10;
document.write("The average is " + average);
</script>
</body>
</html>
The values I put in are 10-100 going up in 10s. So I put in these 10 values "10, 20, 30, 40, 50, 60, 70, 80, 90, 100" And instead of getting the average, I'm getting all of these values side by side.
What am I doing wrong?

grade = prompt("Insert the grade:"); is the problem. The prompt is taking your input as a string, and in JS, adding two strings just concatenates the values. So parse your inputs:
grade = +prompt("Insert the grade:"); //+ is shorthand for casting to a number
Or use parseInt
grade = prompt("Insert the grade:");
var numberGrade = parseInt(grade);
FYI - all the numbers you're adding have to be integers - else it'll just end up as a string again, example:
10 + 10; //20
10 + "10" //1010
10 + 10 + "10" //2010

Change
total = total + grade;
to
total = total + parseInt(grade);
when you write total = total + grade js concatenate total and grade as strings

Related

How can I display addition operation? [duplicate]

I am creating an seat booking page with html/javascript.
This is part of the criteria I am working on:
When Passengers 1 to 4, Add £0.10 to Fare per mile
When number of miles is less than or equal to 10, then Fare per mile is £1.-
The problem is, is that when I try to add together the total cost + cost for passengers, it concatenates the variable (tried it both ways).
Any help would be greatly appreciated.
function MyFunction() {
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value;
if (isNaN(miles) || miles < 1) {
text = "Input not valid";
} else if (miles <= 10) {
cost = miles;
}
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value;
if (passengers >= 1 && passengers <= 4) {
passengerresponse = "OK";
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}
Journey in miles:
<input id="miles" type="number">
<p id="miles2"></p>
Number of passengers:
<input id="passengers" type="number">
<p id="passengers2"></p>
<button type="button" onclick="MyFunction()">Submit</button>
Total cost:
<p id="totalcost"></p>
passengers is a string, not a number. You're doing the same thing as saying cost = 'Santa' + 'Claus'; The fact that it's cost = '1' + '4'; doesn't change the '1' and '4' to a 1 and 4.
The solution is to use parseInt, Number, or one of the method from this answer.
You should convert passengers to numerical value.
Method 1 + unary oprerator
passengers = +document.getElementById("passengers").value;
Method 2 parseInt()
passengers = +document.getElementById("passengers").value;
passengers = parseInt(passengers, 10);
Cost is undefined if you put any miles in greater than 10. When you add undefined to the number of passengers, the result is Not a Number (NaN).
Also, I would recommend you use parseInt on the data you're retrieving from the inputs. Right now you're pulling them in as strings and doing math on them, which only works because Javascript has been smart enough to implicitly cast them as numeric where necessary.
function MyFunction()
{
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value; // miles is a string
miles = parseInt(miles, 10); // convert to numeric base 10
if (isNaN(miles) || miles < 1)
{
text = "Input not valid";
}
else if (miles <= 10)
{
cost = miles;
}
// if miles > 10, cost is undefined
if(!cost) cost = 0;
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value; // passengers is a string
passengers = parseInt(passengers, 10); // convert passengers to a number
if (passengers >= 1 && passengers <= 4 )
{
passengerresponse = "OK";
console.log(cost, passengers);
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}

Application that calculates price depending on quantity in JavaScript

I have this exercise that I am struggling to comprehend the logic to achieve the outcome when qty is more than 3:
An application to calculate the price of pizzas (listed below) that will be purchased during a promotional period. The number of pizzas will be entered by the user.
One large pizza will cost $6.45.
Two large pizzas will cost $12.00.
Three large pizzas will cost $14.00.
Four or more pizzas will use a combination of the above prices to ensure the best price for the customer. For example, the best price for five pizzas would be two pizzas ($12.00) + three pizzas ($14.00).
The algorithm must also take account of all possible situations by using sequence, selection and iteration structures.
Below is my code so far:
let calcOrder = () => {
// get inputs
var qty = document.getElementById("quantity").value;
var price = 6.45;
var price2 = 12.0;
var price3 = 14.0;
var totalPrice;
// validate missing, non-digit, negative inputs
if (qty == "") {
document.getElementById("message").innerHTML = "Missing input";
} else if (isNaN(qty)) {
document.getElementById("message").innerHTML = "Numbers only";
} else if (qty < 0) {
document.getElementById("message").innerHTML =
"Negative numbers are not allowed";
} else {
//calc total
if (qty == 1)
{
totalPrice = price;
}
else if (qty == 2)
{
totalPrice = price2;
}
else if (qty == 3)
{
totalPrice = price3;
}
//output total
document.getElementById("message").innerHTML =
`Total price is $${totalPrice}`;
}
// prevent form from submission
return false;
};
Thank you
you can use division and mod operation to calculate the price:
(this example assuming all check you did valid input are already done)
const qte = document.getElementById("quantity").value;
const price = 6.45;
const price2 = 12.0;
const price3 = 14.0;
let totalPrice;
const total3 = parseInt("" + qte / 3 + "", 10) * price3;
const total2 = parseInt("" + (qte % 3) / 2 + "", 10) * price2;
const total1 = parseInt("" + ((qte % 3) % 2) + "", 10) * price;
totalPrice = total1 + total2 + total3;
document.getElementById("message").innerHTML =
`Total price is $${totalPrice}`;
what is actually happening in the code
well it is basic mathematics, if you want to know how many 3s in your number you divide by 3 and take the integer part or floor of the result, basic division. for example 10 = 3*3 + 1 so you have 3 as a result of that division.
since you only want to apply the price of 3 pizza as top priority you do this division then multiply by the price for 3.
then come the priority for the price of 2 pizzas, but you not interested for the total number of pizzas, only what was left after you payed with the price of 3 pizzas so you do the mod operator (%) with 3 to get was left unpaid, for example 8 = 3*2 + 2, this give us 2 pizzas left unpaid so you apply the price of 2 pizzas.
the you check if a single pizza is left after you paid for 2 pizzas (which would only happen if only a single pizza was left after you paid for 3). if there is single pizza you pay for it otherwise you add nothing.
ps: after paying for pizzas in multiple of three, you only add the price of 2 pizzas or a single one, but never both, otherwise price of 3 pizzas would apply instead.
hope the explanation is clear, if not leave a comment and i'll try to adjust what was not clear.

JavaScript syntax problem - Tip Calculator

Please, could you guys explain this syntax/expression problem?
I was practicing and I tried to create a Tip Calculator which will give me a tip value according to the bill value and percentage.
I can not understand why the expression in the variable finalValues1 does not work.
JSFiddle code result. Thank you very much.
document.getElementById('myForm').addEventListener('submit', function (e) {
e.preventDefault();
var bill, tip, percentage, finalValues1, finalValues2;
bill = document.getElementById('bills').value;
if (bill < 50) { // if bill less $50, give tip of 20%.
percentage = .2;
} else if (bill > 50 && bill < 200) { // if bill greater $50 and less than $200, give tip of 15%.
percentage = .15;
} else {
percentage = .1; // if bill greater than $200, give tip of 10%.
}
tip = bill * percentage;
// I want also to display the final value bills plus tip
finalValues1 = bill + tip; // This code does not work, it is concatenating bills and tip.
finalValues2 = bill * 1 + tip; // this code works and it sums bill plus tip. WHY is that?
document.getElementById('demo').innerHTML = "Tip: " + tip + " and total bill plus tip test1: " + finalValues1 + " test2: " + finalValues2 ;
});
bills.value is a string , not a number
if you want to get a number use bills.valueAsNumber
code:
const myForm = document.getElementById('my-form')
myForm.onsubmit=e=>
{
e.preventDefault()
let bill = myForm.bills.valueAsNumber
, percentage = (bill < 50) ? 0.2 : (bill < 200) ? 0.15 : 0.1
, tip = bill * percentage
;
myForm.demo.textContent = `Tip: ${tip.toFixed(2) } ___ total (bill + tip): ${(bill + tip).toFixed(2)}`
}
<form id="my-form" >
<output name="demo">???</output>
<br>
<br>
<label for="bills">Bill Value :</label>
<input name="bills" autocomplete="off" type="number" required step="0.01">
<br>
<br>
<button type="submit">submit</button>
</form>
as you see it is more easy to use form names instead of elements ID
Use this instead finalValues1 = Math.parseFloat(bill) + Math.parseFloat(tip);
It'll force your code to treat both variables as floats (decimal numbers), rather than strings.
Here is what I would do:
function TipCalc(percent = 20){
this.percent = percent; this.tip = this.total = 0;
this.calc = bill=>{
let t = this.percent/100*bill;
this.tip = t.toFixed(2); this.total = (bill+t).toFixed(2);
return this;
}
}
const tc = new TipCalc;
function billTest(bill){
let p;
if(bill < 50){
p = 20;
}
else if(bill < 200){
p = 15;
}
else{
p = 10;
}
tc.percent = p; tc.calc(bill);
console.log({percent:p, tip:tc.tip, total:tc.total});
}
billTest(15.72); billTest(200.01); billTest(50.01);
Note that tipCalcInstance.tip and tipCalcInstance.total are Strings.
You need to parse the value as a float bill = parseFloat(document.getElementById('bills').value);
And you really should have 0's at the start of your decimals.
You also need to check your order of operations finalValues2 = bill * 1 + tip;
Since multiplication is applied first, this will always just be (bill * 1) + tip.
Change it to bill * (1 + tip)

Running total of single die - Javascript

I am trying to create an application that has a die, singular for dice, on the screen. When you click the die, it will roll and display a number. I also want to keep a running total of each roll.
So far I have it to where each time the button is clicked, the image randomly changes. I'm confused about how to keep a running total of the rolls, however.
Here is the code I have so far.
<html>
<head>
</head>
<body>
<script>
function displaydie() {
var total = 0;
var num = ("src",(Math.floor(Math.random()*6)+1) + ".jpg")
document.getElementById("die").setAttribute("src", (Math.floor(Math.random()*6)+1) + ".jpg")
}
</script>
<img id="die" alt="die"/>
<br/>
<input type="button" value="Click me!" onclick="displaydie()"/>
<span id="total"/></span>
</body>
</html>
Use a global variable to store the total value then add the value of the current dice to the total. For that you need to store the value of the current dice in a variable and use it for the image and to add.
var total = 0;
function displaydie() {
var num = (Math.floor(Math.random() * 6) + 1);
total += num;
document.getElementById("die").setAttribute("src", num + ".jpg")
document.getElementById("total").innerHTML = total;
}
Demo: Fiddle
You want to create a dictionary, and on each roll, add to the number of times you have rolled that number:
var rolls = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
var total=0;
function displaydie()
{
var num= Math.floor(Math.random()*6)+1
rolls[num]+=1
total+=1
document.getElementById("die").setAttribute("src",num + ".jpg")
document.getElementById("total").innerHTML = "Total rolls: "+total+"\n"+"1: "+rolls[1]+" 2: "+rolls[2]+" 3: "+rolls[3]+" 4: "+rolls[4]+" 5: "+rolls[5]+" 6: "+rolls[5]
}
DEMO

Javascript variables not adding two variables correctly, only concatenating

I am creating an seat booking page with html/javascript.
This is part of the criteria I am working on:
When Passengers 1 to 4, Add £0.10 to Fare per mile
When number of miles is less than or equal to 10, then Fare per mile is £1.-
The problem is, is that when I try to add together the total cost + cost for passengers, it concatenates the variable (tried it both ways).
Any help would be greatly appreciated.
function MyFunction() {
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value;
if (isNaN(miles) || miles < 1) {
text = "Input not valid";
} else if (miles <= 10) {
cost = miles;
}
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value;
if (passengers >= 1 && passengers <= 4) {
passengerresponse = "OK";
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}
Journey in miles:
<input id="miles" type="number">
<p id="miles2"></p>
Number of passengers:
<input id="passengers" type="number">
<p id="passengers2"></p>
<button type="button" onclick="MyFunction()">Submit</button>
Total cost:
<p id="totalcost"></p>
passengers is a string, not a number. You're doing the same thing as saying cost = 'Santa' + 'Claus'; The fact that it's cost = '1' + '4'; doesn't change the '1' and '4' to a 1 and 4.
The solution is to use parseInt, Number, or one of the method from this answer.
You should convert passengers to numerical value.
Method 1 + unary oprerator
passengers = +document.getElementById("passengers").value;
Method 2 parseInt()
passengers = +document.getElementById("passengers").value;
passengers = parseInt(passengers, 10);
Cost is undefined if you put any miles in greater than 10. When you add undefined to the number of passengers, the result is Not a Number (NaN).
Also, I would recommend you use parseInt on the data you're retrieving from the inputs. Right now you're pulling them in as strings and doing math on them, which only works because Javascript has been smart enough to implicitly cast them as numeric where necessary.
function MyFunction()
{
var x, text, passengers, passengerresponse, cost;
miles = document.getElementById("miles").value; // miles is a string
miles = parseInt(miles, 10); // convert to numeric base 10
if (isNaN(miles) || miles < 1)
{
text = "Input not valid";
}
else if (miles <= 10)
{
cost = miles;
}
// if miles > 10, cost is undefined
if(!cost) cost = 0;
document.getElementById("miles2").innerHTML = miles;
passengers = document.getElementById("passengers").value; // passengers is a string
passengers = parseInt(passengers, 10); // convert passengers to a number
if (passengers >= 1 && passengers <= 4 )
{
passengerresponse = "OK";
console.log(cost, passengers);
cost += passengers / 10;
}
document.getElementById("passengers2").innerHTML = passengers;
document.getElementById("totalcost").innerHTML = cost;
}

Categories

Resources