Need help making a tip calculator - javascript

I need to make a program that will take a number and multiply it by .15 so you know how much of a tip you need to leave.
I tried to put my bill input into a new variable in my function because I would get the tip total when I took the number () out of my new variable, but doing this lead to nothing happening as JavaScript doesn't know it's a number
<body>
<input id="bill" placeholder ="How much was you meal?" />
<button onclick ="tip()"> submit</button>
<script> let bill = document.querySelector("#bill")
function tip(){
let yourTip = number( bill.value * .15)
let total = yourTip * bill
console.log ("Your tip is $" + yourTip)
console.log ("Your total after the tip is $" + total)
}
</script>
</body>
I don't need to print it on the screen just in the console and the tip % does not need to change.

try this
<input id="bill" type="number" placeholder="How much was you meal?" />
<button onclick="tip()">submit</button>
<script>
function tip() {
var bill = parseInt(document.getElementById("bill").value);
console.log(bill);
let yourTip = bill * 0.15;
let total = yourTip + bill;
console.log("Your tip is $" + yourTip);
console.log("Your total after the tip is $" + total);
}
</script>

Try this:
<style>
body {
text-align: center;
}
</style>
<body>
<input id="bill" placeholder ="How much was you meal?" />
<button onclick ="tip()">Calculate</button>
<h1 id="tip">Tip: $0</h1>
<h1 id="total">Total: $0</h1>
<script> let bill = document.querySelector("#bill")
function tip(){
let bill = document.getElementById('bill').value;
let billNum = parseInt(bill);
let yourTip = billNum * .15;
let total = yourTip + billNum;
document.getElementById('tip').innerHTML = "Tip: $" + yourTip;
document.getElementById('total').innerHTML = "Total: $" + total;
}
</script>
</body>
Let's break it down:
When you get the value of an input field, without specifying the type, JavaScript stores the value as a string. To turn that string into a number, you need to use parseInt(x), which tells the browser that the string is now a number, as you can't multiply a piece of text by a number. You can then multiply that number by the tip percentage.
Additionally, you also multiplied the tip by the bill. I added some styling, as well as using innerHTML instead of console.log() to display the tip and the total bill.

in python, you can do like this
print('Welcome to the tip calculator')
total_bill = float(input("What was the total bill? "))
what_percentage = float(input("What percentage tip would you like to give? "))
tip_percentage = (total_bill * what_percentage) / 100
total_cost = total_bill + tip_percentage
people = int(input("How many people to split the bill? "))
split_value = round(total_cost / people, 2)
print('Each person should pay' + str(split_value))

Related

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)

Adding sum of an array but getting NAN

I'm trying to create a working time clock that allows me to input the number of hours I study everyday and get the total. Am I using parseInt wrong?
<html>
<head>
<title>Time clock</title>
<meta charset="utf-8">
</head>
<body>
<h1 id="header">Time clock</h1>
<p id="greeting"></p>
<input type="text" id="inp"/>
<button onclick="sumit()">Click</button>
<p id="hours"></p>
<script>
greeting.innerHTML = 'How many hours have you studied?'
function sumit(){
let text = parseInt(document.getElementById("inp").value);
let hours = (document.getElementById("hours"));
let total = 0
for (i = 0; i < 10; i++){
total += parseInt(text[i]);
hours.innerHTML = `You have studied a total of ${text + total} hours.`
}
console.log(total)
console.log(text)
}
</script>
</body>
</html>
The text variable is already defined and assigned the value of parseInt. So your total += parseInt(text[i]) is trying to index a number type (e.g. total += 123[0]) which isn't possible. Instead, you can just do total += text, or you can remove the parseInt call when you declare text and then do total += parseInt(text).
With minimal changes, this should work:
function sumit() {
let text = parseInt(document.getElementById("inp").value) || 0;
let hours = document.getElementById("hours");
let total = 0;
total += text;
hours.innerHTML = `You have studied a total of ${total} hours.`;
}
Explanation
parseInt can return NaN, so we use the || operator to let it default to 0
You don't need to loop over anything to sum the number
Even if you were looping over anything, you don't use reference indexes on numbers like you tried to do with text[i]
You don't need to add total to text multiple times

javascript percentages issue

I am trying to calculate the following formula to return a numerical value from 0 - 100 (a grade) depending on the input from a user,
Grade = Exam Worth × Exam Score + (100% − Exam Worth) × Current Grade
and am using the following code to do so,
var total = ExamWorth * ExamScore + (100 - ExamWorth) * CurGrade;
Where my 3 variables are just being pulled in from html like so,
<input type="text" class="form-control" id="aimGrade">
However when I try and calculate I am always getting incorrect answers that I believe have to do not being sure how to convert this to a decimal.
For example an input of ExamWorth = 50 ExamScore = 80 and curGrade = 70 should return a value of 90. Where as i am getting a return of 7500 with the same input.
Perhaps you could make your inputs numbers:
<input type="number" class="form-control" id="aimGrade" min="0" max="100" />
which, as you can see, also allows you to do fancy things like add min and max values.
Then you will still have to use the javascript parseFloat() function:
var fExamWorth = parseFloat(ExamWorth);
Lastly, you may need to revisit your calculation. If your ExamWorth is a value out of 100 (i.e. a percentage), you will need to divide the final result by 100:
var total = (ExamWorth * ExamScore + (100 - ExamWorth) * CurGrade) / 100;
If it is really a decimal/proportion (i.e. a value between 0 and 1) then it should read:
var total = ExamWorth * ExamScore + (1 - ExamWorth) * CurGrade;
I'm guessing you are mixing up 100% and 100.
If ExamWorth is a value between 0 and 1, you should use 1 - ExamWorth instead of 100 - ExamWorth.
var total = ExamWorth * ExamScore + (1 - ExamWorth) * CurGrade;
If ExamWorth is a value between 0 and 100, then you need to divide by 100.
var total = (ExamWorth * ExamScore + (100 - ExamWorth) * CurGrade) / 100;
Using the example you gave, you'd get 75 (instead of 7500), which is the correct number for calculating the final grade.
Your issue isn't converting to a decimal (7500 isn't going to become 90 when you divide by 100). Your algorithm is just wrong.
See algorithm description in the comments.
Also (FYI), there are two things to remember when working with values coming from user-supplied data:
All values extracted from HTML will be strings.
The order of operations in your algorithm might cause string
concatenation instead of mathematical addition.
So, here's an example (click to expand the snippet):
var worth = document.getElementById("worth");
var score = document.getElementById("score");
var grade = document.getElementById("grade");
document.getElementById("calc").addEventListener("click", function(){
// There are a number (no pun intended) of ways to convert strings to numbers
var worthVal = parseInt(worth.value, 10); // explicit
var scoreVal = +score.value; // coercion
var gradeVal = Number(grade.value) // function
// Algorithm:
var examPer = (scoreVal / 100) * worthVal; // % of exam worth achieved
var gradeAvg = gradeVal + examPer / 2; // average of grades
// Order of operations: Parenthesis, Exponents, Multiplication, Division, Addition, Subtraction
// Because of the string, any operand on either side of it will normally be converted to a string
// If we were to try to do all the math at once, we have to be very careful about order of operations
console.log("Result 1: " + (gradeVal + ((scoreVal / 100) * worthVal) / 2));
// But, if we do the math in steps and just put the result with the message, it's much simpler
console.log("Result 2: " + gradeAvg);
});
<input type="text" class="form-control" id="worth" placeholder="exam worth" value="50">
<input type="text" class="form-control" id="score" placeholder="score" value="80">
<input type="text" class="form-control" id="grade" placeholder="grade" value="70">
<input type="button" value="Calculate" id="calc">
UPDATE:
After some thought on this, I don't think the calculation should return 90 as you say you expected. I think it should return 75. Here's why:
You are providing us with the Exam Worth and using that in your calculations, but the only reason you would need that is to get a score (in points), for example:
Exam is weighted at 50
You got 80 percent correct
.8 x 50 = 40 (You got a score of 40 and a percent of 80)
But, to get the overall grade, we don't care about the fact that you got a score of 40 on the exam. We only care about the fact that you got 80%, so the Exam Weight is irrelevant.
To get the correct overall grade, all we need to do is add the two grades (70 and 80) and divide by 2 (75).
So, in that case, the code would be:
var worth = document.getElementById("worth");
var score = document.getElementById("score");
var grade = document.getElementById("grade");
document.getElementById("calc").addEventListener("click", function(){
var scoreVal = +score.value;
var gradeVal = Number(grade.value)
// Algorithm:
var gradeAvg = (scoreVal + gradeVal) / 2; // average of grades
// But, if we do the math in steps and just put the result with the message, it's much simpler
console.log("Result 2: " + gradeAvg);
});
<input type="text" class="form-control" id="worth" placeholder="exam worth" value="50">
<input type="text" class="form-control" id="score" placeholder="score" value="80">
<input type="text" class="form-control" id="grade" placeholder="grade" value="70">
<input type="button" value="Calculate" id="calc">

Values show together instead of as a new value

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

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

Categories

Resources