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">
Related
I have created an algorithm for the base of the natural logarithm with HTML and JS. And this is the code:
HTML: bonl.html
<html>
<head>
<title>bonl</title>
</head>
<body>
<script src="bonl.js"></script>
<input type="number" id="entered">
<input type="button" value="run" onclick="calculate()">
<div id="bonl">
</body>
</html>
and Javascript: bonl.js
function calculate() {
var x = document.getElementById('entered').value;
console.log(x);
var e = (1 + (1/x))**x;
console.log(e);
document.getElementById('bonl').innerHTML = e;
}
First, you assign a number value to <input type="number" id="entered">, and click the button named 'run'. After that, var x in bonl.js will be equal to the number assigned to 'entered'. Then, according to the definition of the base of the natural logarithm (e = lim x->inf (1+(1/x)**x)), the Javascript file will calculate the e. And the result will be displayed by <div id="bonl">.
I hope you noticed that as the value of the x gets larger, javascript file calculates the base of the natural logarithm more accurately.
However, I entered about 10 quadrillion in <input type="number" id="entered">, and I've got the result of 1 instead of 2.71828.., although I get 2.71828 when I enter 100 trillion in <input type="number" id="entered">.
Is my computer dumb to calculate e, or is there an error in my code, or is e = 1?
Yes, your computer is dumb. It can only operate floating point numbers below 2^53. When you go above that, it loses the precision and 1 + small number becomes just 1:
for (let pow = 1; pow < 60; pow++) {
let n = 2 ** pow;
console.log('2^', pow, 'small=', 1 + 1/n, 'e=', (1 + 1/n)**n)
}
Can we do better than that? Yes, we can! Instead of computing e using floating point numbers, let's compute some_big_number * e using Big Integers, which, unlike floats, have unlimited precision. Using BigInts we can compute as many terms of the power series as we want:
let BIG = 10n ** 100n
let f = 1n
let e = BIG
let n = 1n
while (1) {
f = f * n
let eNext = e + BIG / f
if (eNext === e) {
document.write(`e = ${e} <br>`)
document.write(`terms = ${n} <br>`)
break
}
e = eNext
n += 1n
}
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
How can I force these strings to be treated as numbers?
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
(+varname)
So, in your case it's:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
convert the strings to floats with parseFloat(string) or to integers with parseInt(string)
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
You can use this to add numbers:
var x = +num1 + +num2;
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
http://www.crockford.com/
http://javascript.crockford.com/
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
I've always just subtracted zero.
num1-0 + num2-0;
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
Here, you have two options to do this :-
1.You can use the unary plus to convert string number into integer.
2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
Using parsing approach-
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
You can use parseInt to parse a string to a number. To be on the safe side of things, always pass 10 as the second argument to parse in base 10.
num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);
Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.
For example
5 - 7.6 = -2.5999999999999996
#cr05s19xx suggested on a duplicate question:
JavaScript is a bit funny when it comes to numbers and addition.
Giving the following
'20' - '30' = 10; // returns 10 as a number
'20' + '30' = '2030'; // Returns them as a string
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
Use the parseFloat method to parse the strings into floating point numbers:
parseFloat(num1) + parseFloat(num2)
I use this in my project.I use + sign to treat string as a number (in with_interesst variable)
<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest = PHP"+with_interesst;
}
</script>
<div name="printchatbox" id="printchatbox">
<form id="Calculate" class="form-horizontal">
<h2>You Can Use This Calculator Before Submit </h2>
<p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
<option value="40">40 Days</option>
<option value="50">50 Days</option>
<option value="60">60 Days</option>
<option value="70">70 Days</option>
<option value="80">80 Days</option>
<option value="90">90 Days</option>
<option value="100">100 Days</option>
<option value="120">120 Days</option>
</select>
</p>
<h2 id="payment"></h2>
<h2 id ="with_interesst"></h2>
</form>
</div>
Hope it helps
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
You may use like this:
var num1 = '20',
num2 = '30.5';
alert((num1*1) + (num2*1)); //result 50.5
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html
I have 3 textboxes.
<input type="text" name="width" class="width" />
<input type="text" name="width_feet" class="width_feet" />
<input type="text" name="width_inches" class="width_inches" />
End-users can enter a number into textbox width_feet and a number into textbox width_inches. My aim is to perform a calculation to convert the feet and inches into mm and then populate textbox width with the result.
So far I have tried the following which doesn't seem to work very well because the result that populates textbox width is far too large.
jQuery('.width_feet, .width_inches').change(function() {
var feet = jQuery('.width_feet').val();
var inches = jQuery('.width_inches').val();
var total_inches = (feet * 12) + inches;
var mm = total_inches * 25.4;
jQuery('.width').val(mm);
});
JSFIDDLE
Where could I be going wrong?
Use .toFixed() to truncate the unnecessary decimal points,
jQuery('.width_feet, .width_inches').on('input',function() {
var feet = jQuery('.width_feet').val();
var inches = jQuery('.width_inches').val();
var total_inches = (feet * 12) + inches;
var mm = total_inches * 25.4;
jQuery('.width').val(mm.toFixed(1));
});
And I would suggest you to use input event rather than change, since change event only get triggered when the focus got blurred out from the text box.
DEMO
Apart from everything, your code failed to convert the string to number, that is why your calculation went crazy. Try to use parseInt(string,radix) to convert the string to a number.
jQuery('.width_feet, .width_inches').on('input', function () {
var feet = parseInt(jQuery('.width_feet').val(), 10);
var inches = parseInt(jQuery('.width_inches').val(), 10);
var total_inches = ((isNaN(feet) ? 0 : feet) * 12) + (isNaN(inches) ? 0 : inches);
var mm = total_inches * 25.4;
jQuery('.width').val(mm.toFixed(1));
});
DEMO
And I have forgot to tell about .isNaN() function, we have used this in our code because while parsing an empty text box's value the output would be NAN meaning not a number, so in our code we have handled the NAN by replacing it with 0
As per the comment happened, you should use parseFloat() instead of parseInt() since you are dealing with floating point values.
You need to convert both feet and inches to number:
var feet = parseInt(jQuery('.width_feet').val());
var inches = parseInt(jQuery('.width_inches').val());
try this..
I have done in this js fiddle, your problem was with textbox value concatenating.
[http://jsfiddle.net/kka284556/f32rk/1/][1]
try this one,
jQuery('.width_feet, .width_inches').on(function() {
var feet = jQuery('.width_feet').val();
var inches = jQuery('.width_inches').val();
var total_inches = (feet * 12) + inches;
var mm = total_inches * 25.4;
jQuery('.width').val(Math.round(mm).toFixed(2));
});
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
How can I force these strings to be treated as numbers?
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
MDN docs for parseInt
MDN docs for parseFloat
In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!
parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)
Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.
http://jsfiddle.net/EtX6G/
var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];
Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);
function Append(text) {
body.appendChild(document.createTextNode(text));
body.appendChild(document.createElement('br'));
}
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
(+varname)
So, in your case it's:
var num1 = '20',
num2 = '30.5';
var sum = (+num1) + (+num2);
// Just to test it
console.log( sum ); // 50.5
var result = Number(num1) + Number(num2);
convert the strings to floats with parseFloat(string) or to integers with parseInt(string)
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
function addStrings(str1, str2){
str1a = str1.split('').reverse();
str2a = str2.split('').reverse();
let output = '';
let longer = Math.max(str1.length, str2.length);
let carry = false;
for (let i = 0; i < longer; i++) {
let result
if (str1a[i] && str2a[i]) {
result = parseInt(str1a[i]) + parseInt(str2a[i]);
} else if (str1a[i] && !str2a[i]) {
result = parseInt(str1a[i]);
} else if (!str1a[i] && str2a[i]) {
result = parseInt(str2a[i]);
}
if (carry) {
result += 1;
carry = false;
}
if(result >= 10) {
carry = true;
output += result.toString()[1];
}else {
output += result.toString();
}
}
output = output.split('').reverse().join('');
if(carry) {
output = '1' + output;
}
return output;
}
You can use this to add numbers:
var x = +num1 + +num2;
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
http://www.crockford.com/
http://javascript.crockford.com/
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
I've always just subtracted zero.
num1-0 + num2-0;
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
function sum(){
var x,y,z;
x = Number(document.getElementById("input1").value);
y = Number(document.getElementById("input2").value);
z = x + y;
document.getElementById("result").innerHTML = z ;
}
If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.
const bigInt = require('big-integer')
bigInt("999").add("1").toString() // output: "1000"
Here, you have two options to do this :-
1.You can use the unary plus to convert string number into integer.
2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
Using parsing approach-
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
You can use parseInt to parse a string to a number. To be on the safe side of things, always pass 10 as the second argument to parse in base 10.
num1 = parseInt(num1, 10);
num2 = parseInt(num2, 10);
alert(num1 + num2);
Make sure that you round your final answer to less than 16 decimal places for floats as java script is buggy.
For example
5 - 7.6 = -2.5999999999999996
#cr05s19xx suggested on a duplicate question:
JavaScript is a bit funny when it comes to numbers and addition.
Giving the following
'20' - '30' = 10; // returns 10 as a number
'20' + '30' = '2030'; // Returns them as a string
The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
Use the parseFloat method to parse the strings into floating point numbers:
parseFloat(num1) + parseFloat(num2)
I use this in my project.I use + sign to treat string as a number (in with_interesst variable)
<script>
function computeLoan(){
var amount = document.getElementById('amount').value;
var interest_rate = document.getElementById('interest_rate').value;
var days = document.getElementById('days').value;
var interest = (amount * (interest_rate * .01)) / days;
var payment = ((amount / days) + interest).toFixed(2);
var with_interest = (amount * (interest_rate * .01));
var with_interesst = (+amount * (interest_rate * .01)) + (+amount);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById('payment').innerHTML = "Target Daily = PHP"+payment;
document.getElementById('with_interesst').innerHTML = "Amount w/Interest = PHP"+with_interesst;
}
</script>
<div name="printchatbox" id="printchatbox">
<form id="Calculate" class="form-horizontal">
<h2>You Can Use This Calculator Before Submit </h2>
<p>Loan Amount: PHP<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate: <input id="interest_rate" type="number" min="0" max="100" value="10" step=".1" onchange="computeLoan()">%</p>
<p>Term<select id="days" type="number" min="1" max="72" step=".1" onchange="computeLoan()">
<option value="40">40 Days</option>
<option value="50">50 Days</option>
<option value="60">60 Days</option>
<option value="70">70 Days</option>
<option value="80">80 Days</option>
<option value="90">90 Days</option>
<option value="100">100 Days</option>
<option value="120">120 Days</option>
</select>
</p>
<h2 id="payment"></h2>
<h2 id ="with_interesst"></h2>
</form>
</div>
Hope it helps
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
You may use like this:
var num1 = '20',
num2 = '30.5';
alert((num1*1) + (num2*1)); //result 50.5
When apply *1 in num1, convert string a number.
if num1 contains a letter or a comma, returns NaN multiplying by 1
if num1 is null, num1 returns 0
kind regards!!!
Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.
Enter the first number: <input type="text" id="num1" /><br />
Enter the seccond number: <input type="text" id="num2" /><br />
<input type="button" onclick="call()" value="Add"/>
<script type="text/javascript">
function call(){
var q=parseInt(document.getElementById("num1").value);
var w=parseInt(document.getElementById("num2").value);
var result=q+w;
}
</script>
for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html
How can I round down a number in JavaScript?
math.round() doesn't work because it rounds it to the nearest decimal.
I'm not sure if there is a better way of doing it other than breaking it apart at the decimal point at keeping the first bit. There must be...
Using Math.floor() is one way of doing this.
More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
Round towards negative infinity - Math.floor()
+3.5 => +3.0
-3.5 => -4.0
Round towards zero can be done using Math.trunc(). Older browsers do not support this function. If you need to support these, you can use Math.ceil() for negative numbers and Math.floor() for positive numbers.
+3.5 => +3.0 using Math.floor()
-3.5 => -3.0 using Math.ceil()
Math.floor() will work, but it's very slow compared to using a bitwise OR operation:
var rounded = 34.923 | 0;
alert( rounded );
//alerts "34"
EDIT Math.floor() is not slower than using the | operator. Thanks to Jason S for checking my work.
Here's the code I used to test:
var a = [];
var time = new Date().getTime();
for( i = 0; i < 100000; i++ ) {
//a.push( Math.random() * 100000 | 0 );
a.push( Math.floor( Math.random() * 100000 ) );
}
var elapsed = new Date().getTime() - time;
alert( "elapsed time: " + elapsed );
You can try to use this function if you need to round down to a specific number of decimal places
function roundDown(number, decimals) {
decimals = decimals || 0;
return ( Math.floor( number * Math.pow(10, decimals) ) / Math.pow(10, decimals) );
}
examples
alert(roundDown(999.999999)); // 999
alert(roundDown(999.999999, 3)); // 999.999
alert(roundDown(999.999999, -1)); // 990
Rounding a number towards 0 (aka "truncating its fractional part") can be done by subtracting its signed fractional part number % 1:
rounded = number - number % 1;
Like Math.floor (rounds towards -Infinity) this method is perfectly accurate.
There are differences in the handling of -0, +Infinity and -Infinity though:
Math.floor(-0) => -0
-0 - -0 % 1 => +0
Math.floor(Infinity) => Infinity
Infinity - Infinity % 1 => NaN
Math.floor(-Infinity) => -Infinity
-Infinity - -Infinity % 1 => NaN
Math.floor(1+7/8)
To round down towards negative infinity, use:
rounded=Math.floor(number);
To round down towards zero (if the number can round to a 32-bit integer between -2147483648 and 2147483647), use:
rounded=number|0;
To round down towards zero (for any number), use:
if(number>0)rounded=Math.floor(number);else rounded=Math.ceil(number);
Was fiddling round with someone elses code today and found the following which seems rounds down as well:
var dec = 12.3453465,
int = dec >> 0; // returns 12
For more info on the Sign-propagating right shift(>>) see MDN Bitwise Operators
It took me a while to work out what this was doing :D
But as highlighted above, Math.floor() works and looks more readable in my opinion.
This was the best solution I found that works reliably.
function round(value, decimals) {
return Number(Math.floor(parseFloat(value + 'e' + decimals)) + 'e-' + decimals);
}
Credit to: Jack L Moore's blog
You need to put -1 to round half down and after that multiply by -1 like the example down bellow.
<script type="text/javascript">
function roundNumber(number, precision, isDown) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = 0;
if (isDown) {
tempNumber = -tempNumber;
roundedTempNumber = Math.round(tempNumber) * -1;
} else {
roundedTempNumber = Math.round(tempNumber);
}
return roundedTempNumber / factor;
}
</script>
<div class="col-sm-12">
<p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script>
</p>
<p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p>
</div>
Here is math.floor being used in a simple example. This might help a new developer to get an idea how to use it in a function and what it does. Hope it helps!
<script>
var marks = 0;
function getRandomNumbers(){ // generate a random number between 1 & 10
var number = Math.floor((Math.random() * 10) + 1);
return number;
}
function getNew(){
/*
This function can create a new problem by generating two random numbers. When the page is loading as the first time, this function is executed with the onload event and the onclick event of "new" button.
*/
document.getElementById("ans").focus();
var num1 = getRandomNumbers();
var num2 = getRandomNumbers();
document.getElementById("num1").value = num1;
document.getElementById("num2").value = num2;
document.getElementById("ans").value ="";
document.getElementById("resultBox").style.backgroundColor = "maroon"
document.getElementById("resultBox").innerHTML = "***"
}
function checkAns(){
/*
After entering the answer, the entered answer will be compared with the correct answer.
If the answer is correct, the text of the result box should be "Correct" with a green background and 10 marks should be added to the total marks.
If the answer is incorrect, the text of the result box should be "Incorrect" with a red background and 3 marks should be deducted from the total.
The updated total marks should be always displayed at the total marks box.
*/
var num1 = eval(document.getElementById("num1").value);
var num2 = eval(document.getElementById("num2").value);
var answer = eval(document.getElementById("ans").value);
if(answer==(num1+num2)){
marks = marks + 10;
document.getElementById("resultBox").innerHTML = "Correct";
document.getElementById("resultBox").style.backgroundColor = "green";
document.getElementById("totalMarks").innerHTML= "Total marks : " + marks;
}
else{
marks = marks - 3;
document.getElementById("resultBox").innerHTML = "Wrong";
document.getElementById("resultBox").style.backgroundColor = "red";
document.getElementById("totalMarks").innerHTML = "Total Marks: " + marks ;
}
}
</script>
</head>
<body onLoad="getNew()">
<div class="container">
<h1>Let's add numbers</h1>
<div class="sum">
<input id="num1" type="text" readonly> + <input id="num2" type="text" readonly>
</div>
<h2>Enter the answer below and click 'Check'</h2>
<div class="answer">
<input id="ans" type="text" value="">
</div>
<input id="btnchk" onClick="checkAns()" type="button" value="Check" >
<div id="resultBox">***</div>
<input id="btnnew" onClick="getNew()" type="button" value="New">
<div id="totalMarks">Total marks : 0</div>
</div>
</body>
</html>
Math.round(3.14159 * 100) / 100 // 3.14
3.14159.toFixed(2); // 3.14 returns a string
parseFloat(3.14159.toFixed(2)); // 3.14 returns a number
Math.round(3.14159) // 3
Math.round(3.5) // 4
Math.floor(3.8) // 3
Math.ceil(3.2) // 4