Calculation in jquery - javascript

Trying to get Break Even Point (BEP) and selling value using jquery.
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
$("#cost").on("change keyup paste", function() {
var cost = Number($('#cost').val());
var text
var total_cost = roundToTwo(((cost * 18) / 100) + cost);
var profit = -0.5;
var sell = cost + 0.01;
while (profit <= 0) {
sell = sell + 0.01;
profit = roundToTwo(sell - total_cost);
text += "<br />New Sell " + sell + " and profit " + profit;
}
var bep = roundToTwo(sell - total_cost);
$('#bep_display').text(bep);
document.getElementById("testing").innerHTML = text;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="number" class="form-control" id="cost" placeholder="cost" name="cost">
<h1 id="bep_display">
</h1>
<p id="testing"></p>
Now by running the above code, I entered 1 in the input, so the result (BEP) should be 0, but it gives NaN

Because your answer returns with e so it shows NaN. Try:
var bep = parseFloat(sell - total_cost).toFixed(8);
This will give you the result 0.00000000.
If you need a result as 0. Add:
bep = roundToTwo(bep);
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
$("#cost").on("change keyup paste", function() {
var cost = Number($('#cost').val());
var text
var total_cost = roundToTwo(((cost * 18) / 100) + cost);
var profit = -0.5;
var sell = cost + 0.01;
while (profit <= 0) {
sell = sell + 0.01;
profit = roundToTwo(sell - total_cost);
text += "<br />New Sell " + sell + " and profit " + profit;
}
var bep = parseFloat(sell - total_cost).toFixed(8);
bep = roundToTwo(bep);
$('#bep_display').text(bep);
document.getElementById("testing").innerHTML = text;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="number" class="form-control" id="cost" placeholder="cost" name="cost">
<h1 id="bep_display">
</h1>
<p id="testing"></p>

The problem is with this line :
var bep = roundToTwo(sell - total_cost);
One solution is to fixed your decimals, for example :
var bep = roundToTwo(sell.toFixed(8) - total_cost.toFixed(8));

Related

If statement returning true when comparing user input vs sum of numbers

Ok, so my project is to make a math quiz site. I have to have 2 numbers randomly generated and the user needs to fill in the number. The user needs to also needs to be able to choose their operation. Now my problem is under my second function I am trying to go by each operation and have the computed answer compared to the user input. As of right now my code either turns positive for all operations or depending on how many = I use it says sorry. I have tried adding another condition of if the add button is checked.
`
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1><b>Pirate Math</b></h1>
<p id= "bubble"><b>Ahoy Matey!</b> Can you help me practice my math?</p>
<img id = "g1" src = "images/g1_t.png" alt= "Pirate Girl" height="200 px" width = "150px"/>
<ul>
<li><p id = "num1"></p></li>
<li><p id = "opBox"></p></li>
<li><p id = "num2"></p></li>
</ul>
<input type="number" id = "answerBox">
<br>
<br>
<button id= "checkAns">Check Answer</button>
<br>
<br>
<br>
<fieldset>
<h3>Choose your <br> operation!</h3>
<input type="radio" id="op1" name="op" value="add">
<label for="op1"> + </label>
<br>
<input type="radio" id="op2" name="op" value="sub">
<label for="op2"> - </label>
<br>
<input type="radio" id="op3" name="op" value="mult">
<label for="op3"> x </label>
<br>
<input type="radio" id="op4" name="op" value="divide">
<label for="op4"> ÷ </label>
<br>
<button id= "opPick">Click to pick!</button>
</fieldset>
<br>
<p div class="copyright"><em><small>© 2021 Ashley Kohn</small></em></div>
<script>
//button on click op choose
document.getElementById("opPick").addEventListener("click", function operation(){
var op1 = document.getElementById("op1");
var op2 = document.getElementById("op2");
var op3 = document.getElementById("op3");
var op4 = document.getElementById("op4");
console.log("op1 " + op1.checked);
console.log("op2 " + op2.checked);
console.log("op3 " + op3.checked);
console.log("op4 " + op4.checked);
//Addition
if ( op1.checked){
var addNum1 = Math.floor(Math.random() * (20 - 1 + 1));
var addNum2 = Math.floor(Math.random() * (20 - 1 + 1));
console.log("this is with " + (Math.floor(addNum1) + 1));
document.getElementById("num1").innerHTML = addNum1;
document.getElementById("num2").innerHTML = addNum2;
document.getElementById("opBox").innerHTML = "+";
var sum=0;
sum=Number(addNum1)+Number(addNum2);
console.log("SUM is: " + sum);
}
//subtraction
if ( op2.checked){
var subNum1 = Math.floor(Math.random() * (20 - 1 + 1));
var subNum2 = Math.floor(Math.random() * (20 - 1 + 1));
console.log("this is sub " + (Math.floor(subNum1) + 1));
document.getElementById("num1").innerHTML = subNum1;
document.getElementById("num2").innerHTML = subNum2;
document.getElementById("opBox").innerHTML = "&#8722";
var dif=0;
dif=Number(subNum1)-Number(subNum2);
console.log("DIF is: " + dif);
}
//multipulcation
if ( op3.checked){
var multNum1 = Math.floor(Math.random() * (20 - 1 + 1));
var multNum2 = Math.floor(Math.random() * (20 - 1 + 1));
console.log("this is with " + (Math.floor(multNum1) + 1));
document.getElementById("num1").innerHTML = multNum1;
document.getElementById("num2").innerHTML = multNum2;
document.getElementById("opBox").innerHTML = "×";
var prod =0;
prod=Number(multNum1)* Number(multNum2);
console.log("PROd is: " + prod);
}
//division
if ( op4.checked){
var divideNum1 = Math.floor(Math.random() * (20 - 1 + 1));
var divideNum2 = Math.floor(Math.random() * (20 - 1 + 1));
console.log("this is with divide " + (Math.floor(divideNum1) + 1));
document.getElementById("num1").innerHTML = divideNum1;
document.getElementById("num2").innerHTML = divideNum2;
document.getElementById("opBox").innerHTML = "÷";
var divi=0;
divi=Number(divideNum1)/ Number(divideNum2);
console.log("DIVI is: " + divi);
} // closing if
}); // closing function 1
document.getElementById("checkAns").addEventListener("click", function math(){ // supposed to solve the addition
var userNum = document.getElementById("answerBox").value;
var addNum1 = document.getElementById("num1");
var addNum2 = document.getElementById("num2");
var sum = Number(addNum1) + Number(addNum2);
var subNum1 = Math.floor(Math.random() * (20 - 1 + 1));
var subNum2 = Math.floor(Math.random() * (20 - 1 + 1));
var dif = Number(subNum1)-Number(subNum2);
var multNum1 = Math.floor(Math.random() * (20 - 1 + 1));
var multNum2 = Math.floor(Math.random() * (20 - 1 + 1));
var prod = Number(multNum1)* Number(multNum2);
var divideNum1 = Math.floor(Math.random() * (20 - 1 + 1));
var divideNum2 = Math.floor(Math.random() * (20 - 1 + 1));
var divi = Number(divideNum1)/ Number(divideNum2);
if (Number(sum) == Number(userNum)){
console.log("yay!");
}//if statement closed
/*else if (dif = Number(userNum) && op2.checked){
console.log("yay!");
}//if statement closed
else if (prod = Number(userNum) && op3.checked){
console.log("yay!");
}//if statement closed
else if (divi = Number(userNum)&& op4.checked){
console.log("yay!");
}//if statement closed */
else{
console.log("sorry!");
}
})//closing function 2`
var addNum1 = document.getElementById("num1"); gets the element, you want the value inside.
Try addNum1.value to access the value. Currently it always evaluates to true because you are comparing two objects.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

Problem with solving equations in JavaScript [duplicate]

This question already has answers here:
issue with comparing two numbers in javascript
(5 answers)
Closed 1 year ago.
This code is supposed to give you an equation and when you solve it, you get another one in three seconds. You can choose the amount of equations you're getting and how "high" the math is. And it will give you an alert when you did your chosen amount of questions. This code returns no error but it never gives me the alert as it is supposed to. How do I fix this? (I know I am a beginner so my code is a bit messy)
var rand1, rand2, text1, text2
let count = 0;
var correct = 0;
function button() {
text1 = document.getElementById("number").value;
text2 = document.getElementById('questions').value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " +
Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check() {
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if (answer == text11) {
var h = "<input type='number' id='id'> " +
" <button onclick=' check() '> check </button> " +
correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
correct = correct + 1;
count = count + 1;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " +
" <button onclick=' check() '> check </button> "
+ correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count === text2) {
alert(correct + '/' + text2);
}
function wait() {
button()
}
}
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id='but'> ok </button>
<div id='div'> </div>
Aside from using strict equality, you're also displaying the correct var before updating the value when it's correct. This should work how you want it:
var rand1, rand2, text1, text2
let count = 0;
let correct = 0;
function button() {
text1 = document.getElementById("number").value;
text2 = document.getElementById('questions').value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " + Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check() {
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if (answer == text11) {
count = count + 1;
correct = correct + 1;
var h = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count == text2) {
alert(correct + '/' + text2);
}
function wait() {
button()
}
}
<html>
<body>
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id='but'> ok </button>
<div id='div'> </div>
count is an integer and text2 is a string so the if statement comparing count and text2 will never return true. Therefore that block delivering the alert will never fire.
I would simply use javascript's parstInt function to make sure text2 is an integer
text2 = parseInt(document.getElementById('questions').value);

My javascript output flashes for a second and then disappears

My Javascript is giving out the right output at the initial glance i get but for some reason the output flashes for a quick second and then disappears
I am not using any frameworks and I am working on basic Javascript.
I've tried checking the console for the output but even there it just flashes. I also tried it on firefox and edge and the same issue arises
function MathRandom2() {
let questionList = [];
questionList.length = 10;
let result = [];
let operator = ['+', '-', '*', '/'];
var numberRand = 0;
// question variable will create the question based off the level choice. numberRand will be the limit.
let question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
let total = 0;
var username = document.getElementById("username").value;
//Line 12 to line 37 will check the radio button selection.
if (document.getElementById("beginner").checked) {
let result = confirm("Hey " + username + "! You have selected the beginner difficulty. Are you sure you wish to proceed?");
if (result == true) {
numberRand = 10;
} else {
return 0;
}
} else if (document.getElementById("intermediate").checked) {
let result = confirm("Hey " + username + "! You have selected the intermediate difficulty. Are you sure you wish to proceed?");
if (result == true) {
numberRand = 20;
} else {
return 0;
}
} else if (document.getElementById("advanced").checked) {
let result = confirm("Hey " + username + "! You have selected the advanced difficulty. Are you sure you wish to proceed?");
if (result == true) {
numberRand = 100;
} else {
return 0;
}
}
for (let i = 0; i < questionList.length; i++) {
let answer = parseInt(prompt("What is the answer to " + question));
let correct = "<span style='background-color: #12CA00'>Your Answer to question </span> " + "<span style='background-color: #12CA00'>" + i + "</span>" + "<span style='background-color: #12CA00'> is correct</span>"
let wrong = "<span style='background-color: #ca0002'>Your Answer to question </span> " + "<span style='background-color: #ca0002'>" + i + "</span>" + "<span style='background-color: #ca0002'> is wrong</span>"
if (answer === eval(question)) {
result.push(correct);
question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
total += 2;
} else {
result.push(wrong);
question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
}
}
let display = result.join("</br>") + "</br>" + "You have got " + total + " marks";
document.getElementById("result").innerHTML = display;
console.log(display);
}
<div id="infoCol_main" class="infoCol_main">
<script src="../Javascript/tute09.js"></script>
<form>
<h1>Welcome</h1>
<fieldset>
<label>Please enter your name here: <br><input type="text" id="username" name="username" required></label><br>
<label>Please choose your difficulty level: <br>
<input type="radio" name="difficulty" id="beginner" value="Beginner" required>Beginner<br>
<input type="radio" name="difficulty" id="intermediate" value="Intermediate" required>Intermediate<br>
<input type="radio" name="difficulty" id="advanced" value="Advanced" required>Advanced<br>
</label>
<div class="buttonHold">
<input type="submit" onclick="MathRandom2()" value="Begin">
</div>
</fieldset>
</form>
</div>
<div>
<p id="result"></p>
</div>
I need it to show a list of answers with the background changed to red or green depending on if the answer was wrong or right respectively. The output is correct and I see it but its only there for a split second before it disappearsenter code here
Use preventDefault()
The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
function MathRandom2() {
const form = document.getElementById('form');
form.addEventListener("submit", function(event){
event.preventDefault(); // prevents form from submitting
})
function MathRandom2() {
const form = document.getElementById('form');
form.addEventListener("submit", function(event){
event.preventDefault();
})
let questionList = [];
questionList.length = 10;
let result = [];
let operator = ['+', '-', '*', '/'];
var numberRand = 0;
// question variable will create the question based off the level choice. numberRand will be the limit.
let question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
let total = 0;
var username = document.getElementById("username").value;
//Line 12 to line 37 will check the radio button selection.
if (document.getElementById("beginner").checked) {
let result = confirm("Hey " + username + "! You have selected the beginner difficulty. Are you sure you wish to proceed?");
if (result == true) {
numberRand = 10;
} else {
return 0;
}
} else if (document.getElementById("intermediate").checked) {
let result = confirm("Hey " + username + "! You have selected the intermediate difficulty. Are you sure you wish to proceed?");
if (result == true) {
numberRand = 20;
} else {
return 0;
}
} else if (document.getElementById("advanced").checked) {
let result = confirm("Hey " + username + "! You have selected the advanced difficulty. Are you sure you wish to proceed?");
if (result == true) {
numberRand = 100;
} else {
return 0;
}
}
for (let i = 0; i < questionList.length; i++) {
let answer = parseInt(prompt("What is the answer to " + question));
let correct = "<span style='background-color: #12CA00'>Your Answer to question </span> " + "<span style='background-color: #12CA00'>" + i + "</span>" + "<span style='background-color: #12CA00'> is correct</span>"
let wrong = "<span style='background-color: #ca0002'>Your Answer to question </span> " + "<span style='background-color: #ca0002'>" + i + "</span>" + "<span style='background-color: #ca0002'> is wrong</span>"
if (answer === eval(question)) {
result.push(correct);
question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
total += 2;
} else {
result.push(wrong);
question = (Math.floor(Math.random() * numberRand) + 1) + operator[Math.floor(Math.random() * 4)] + (Math.floor(Math.random() * numberRand) + 1);
}
}
let display = result.join("</br>") + "</br>" + "You have got " + total + " marks";
document.getElementById("result").innerHTML = display;
}
<div id="infoCol_main" class="infoCol_main">
<script src="../Javascript/tute09.js"></script>
<form id="form">
<h1>Welcome</h1>
<fieldset>
<label>Please enter your name here: <br><input type="text" id="username" name="username" required></label><br>
<label>Please choose your difficulty level: <br>
<input type="radio" name="difficulty" id="beginner" value="Beginner" required>Beginner<br>
<input type="radio" name="difficulty" id="intermediate" value="Intermediate" required>Intermediate<br>
<input type="radio" name="difficulty" id="advanced" value="Advanced" required>Advanced<br>
</label>
<div class="buttonHold">
<input type="submit" onclick="MathRandom2()" value="Begin">
</div>
</fieldset>
</form>
</div>
<div>
<p id="result"></p>
</div>
The default behaviour of the input is to refresh the page once the function has passed. All you need to do is to add this to the top of your function:
function MathRandom2() {
event.preventDefault();
...

How can I save best guess (higher/lower)

for example my toGuess number is 50 and my best lower guess is 48 but I guess 47 and it changes my best lower guess to that 47.
What I mean by this is that I want it not go lower anymore
Same thing with the higher guess
I want it to save/lock my best guess to the closest
'use strict'
var toGuess = Math.floor(Math.random() * (100 + 1));
console.log("To Guess: " + toGuess);
var guess = undefined;
var amount = 0;
var bestHigher = 100;
var bestLower = 0;
var hint = document.getElementById('hint');
var numbers = document.getElementById('numbers');
var lower = document.getElementById('lower');
var higher = document.getElementById('higher');
function GuessDone() {
var put = document.getElementById('number').value;
guess = Number(put);
console.log("Guess: " + guess);
document.getElementById('form').reset();
amount = amount + 1;
console.log("Guesses " + amount);
var numberDif = Number(toGuess) - Number(put);
var bestLower = Number(put) > toGuess;
var bestHigher = Number(put) < toGuess;
if (numberDif > bestLower) {
bestLower = Number(put);
console.log("Lower " + bestLower);
}
if (numberDif < bestHigher) {
bestHigher = Number(put);
console.log("Higher " + bestHigher);
}
if (guess > toGuess) {
hint.innerHTML = "You need to guess lower";
higher.innerHTML = "Best guess above " + bestHigher;
} else if (guess < toGuess) {
hint.innerHTML = "You need to guess higher";
lower.innerHTML = "Best guess below " + bestLower;
} else {
hint.innerHTML = "Congratz, " + toGuess + " was right! Guesses " + amount;
var print = "";
var i;
for (i = 0; i <= toGuess; i++) {
print += i + "<br>";
}
numbers.innerHTML = print;
}
return false;
EDIT
This is my html
<form id="form">
<label for="number">Guess number between 0-100: </label>
<input id="number" type="text" name="number">
<button type="submit">Guess</button>
</form>
<p id="lower"></p>
<p id="higher"></p>
<p id="hint"></p>
<p id="numbers"></p>
<script src="numbergame.js"></script>
FIDDLE
https://jsfiddle.net/d3761nbj/2/

How can I center a header above a table according to the table's width (not the entire page's width)?

So here's my code, but I don't know what to add to it to make it center the text according to the tables width.
<script type="text/javascript">
"use strict";
var principal;
var rate;
var numyears;
var yearlist;
var simpleinterest;
var compoundinterest;
yearlist = 1;
principal = Number(prompt("Enter Principal"));
rate = Number(prompt("Enter rate (percentage value)"));
numyears = Number(prompt("Enter number of years"));
document.writeln("<h1>Table for $" + principal + " at " + rate + "%</h1>");
document.writeln("<table id=\"interest\"><th>Year</th><th>SimpleInterest</th><th>CompoundInterest</th>");
while (yearlist <= numyears) {
compoundinterest = Math.pow((1+rate/100), yearlist) * principal;
simpleinterest = (principal * yearlist * rate/100) + principal;
document.writeln("<tr><td>" + yearlist + "</td><td>$" + simpleinterest + "</td><td>$" + compoundinterest + "</td></tr>");
yearlist++;
}
</script>
Your question is not clear. but on a guess, I had created this
<script type="text/javascript">
"use strict";
var principal;
var rate;
var numyears;
var yearlist;
var simpleinterest;
var compoundinterest;
yearlist = 1;
principal = Number(prompt("Enter Principal"));
rate = Number(prompt("Enter rate (percentage value)"));
numyears = Number(prompt("Enter number of years"));
document.writeln("<table id=\"interest\">");
document.writeln("<tr><td colspan='3' align='center'><h1 align='center'>Table for $" + principal + " at " + rate + "%</h1></td></tr><th>Year</th><th>SimpleInterest</th><th>CompoundInterest</th>");
while (yearlist <= numyears) {
compoundinterest = Math.pow((1+rate/100), yearlist) * principal;
simpleinterest = (principal * yearlist * rate/100) + principal;
document.writeln("<tr><td>" + yearlist + "</td><td>$" + simpleinterest + "</td><td>$" + compoundinterest + "</td></tr>");
yearlist++;
}
</script>

Categories

Resources