Hello I am trying to do a simple calculation of three values: a + b * c but getting wrong total. If a is 10 and b is 10 it would be 20 multiplied by c which is 2.4. I should get 48 as total. Currently getting 2424.
function compute() {
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
var total = (a + b) * c;
$('#total').val(total);
}
$('#a, #b, #c').change(compute);
Basic maths : multiplication have precedence over addition.
So in your code, a is additionned to the result of b*c .
Use :
var total = (a + b) * c;
a + b * c is being evaluated as a + (b * c)
What you need is (a + b) * c
Precedence: Brackets > Division > Multiplication > Addition > Subtraction
In your question, you stated that you get 1024. Getting 1024 is impossible. You should get 34. (Check your calculation elsewhere)
a + (b * c) = 10 + (10 * 2.4) = 34
If you want to add a to b BEFORE multiplying, you'll need to use parentheses.
That's because the multiplication oprator has higher precedence than addition.
(a + b) * c
try after parsing the values like:
var total = (parseFloat(a) + parseFloat(b)) * parseFloat(c);
$(document).ready(function() {
function compute() {
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
var total = (parseInt(a,10) + parseInt(b,10)) * parseFloat(c); alert(total);
$('#total').val(total);
}
$('#a, #b, #c').change(compute);
});
Check DEMO
Your variables are strings. Use parseFloat function.
"10" + "10"*"2.4" = "10"+ 24 = "1024"
Related
I have a program that reads a specific text file from a coding challenge that I've recieved and it takes the numbers and puts it into an array for me to solve a quadratic equation. When I go to display my answers I keep getting the NaN error on all of my values and I cant find where I messed up.
CODE
var lines = data[0].split("/n");
var numQuads = lines[0];
for (var i = 1; i < numQuads; i++){
var fields = lines[i].split(",");
var a = fields[0];
var b = fields[1];
var c = fields[2];
}
a = parseInt();
b = parseInt();
c = parseInt();
var discr = (b * b) - (4 * (a * c));
var sqrDiscr = Math.sqrt(discr);
var x = (-b + sqrDiscr) / (2*a);
var y = (-b - sqrDiscr) / (2*a);
var outputL = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has no real roots!";
var outputW = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has roots x = " + x + " and x = " + y;
if (discr >= 0) {
output += outputW + "\n";
}
else {
output += outputL + "\n\n";
}
You did not provide an argument to the parseInt function. It works like this: parseInt("2") for example. You probably want to use parseFloat instead of parseInt.
Another remark: your data array is undefined.
you have insert String in parseInt()
a = parseInt("67");
b = parseInt("3");
c = parseInt("2");
Should probably be:
a = parseInt(a);
b = parseInt(b);
c = parseInt(c);
the problem was var lines = data[0].split("/n");
I used the wrong character. It was supposed to be var lines = data[0].split("\n");
The problem is that you are not parsing anything with your parse int.
Take a look here for some docs on parseInt.
Anyway that's how it should look like in your code:
a = parseInt(a, 10);
b = parseInt(b, 10);
c = parseInt(c, 10);
d = parseInt(d, 10);
EDIT: following the suggestion of #d3l I looked into the parseInt parameters, according to this question there could be some unexpected behaviours of the parseInt function without adding the radix parameter. Hence I added it to my solution.
Assuming you are parsing integers we can specify 10 as base.
We have the following code in Mongoose schema trying to convert money to integer to save in MongoDB:
amount: { type: Number, get: getAmount, set: setAmount, required: true}
function setAmount(num) {
return num * 100;
}
function getAmount(num) {
return (num / 100).toFixed(2);
}
However saving 64.49 we still end up with this in MongoDB documents:
"amount": 6448.999999999999
How do we fix this?
To avoid these kind of precision issue on "money" variables, I always use "cents" as unit.
Don't store 15.24$, store 1524 cents in your code.
Then do all operation using integers.
Then use cents => dollars conversion only for display, by adding "." separator before the last two characters.
Consider using BigNumber: http://mikemcl.github.io/bignumber.js/
Small example (in the console):
> 0.2 * 0.4
< 0.08000000000000002
And with BigNumber:
> var a = new BigNumber(0.2);
> var b = new BigNumber(0.4);
> var c = a.times(b);
> c.valueOf();
< "0.08"
Does this satisfy your needs?
function convert(number) {
const [i, d] = ('' + number).split(/\./);
const a = +i * 100;
const b = +(d || '0').slice(0, 2);
const c = +(d || '0').slice(2)? 1 : 0;
return a + b + c;
}
Here is the old version that didn't round up the trailing .0099999:
function convert(number) {
const [a, b] = ('' + number).split(/\./);
return +a * 100 + +(b || '0').slice(0, 2);
}
It receives 1 number and returns the same number multiplied by 100.
OBJECTIVE
Given two numbers in an array, sum all the numbers including (and between) both integers (e.g [4,2] -> 2 + 3 + 4 = 9).
I've managed to solve the question but was wondering if there is a more elegant solution (especially using Math.max and Math.min) - see below for more questions...
MY SOLUTION
//arrange array for lowest to highest number
function order(min,max) {
return min - max;
}
function sumAll(arr) {
var list = arr.sort(order);
var a = list[0]; //smallest number
var b = list[1]; //largest number
var c = 0;
while (a <= b) {
c = c + a; //add c to itself
a += 1; // increment a by one each time
}
return c;
}
sumAll([10, 5]);
MY QUESTION(S)
Is there a more efficient way to do this?
How would I use Math.max() and Math.min() for an array?
Optimum algorithm
function sumAll(min, max) {
return ((max-min)+1) * (min + max) / 2;
}
var array = [4, 2];
var max = Math.max.apply(Math, array); // 4
var min = Math.min.apply(Math, array); // 2
function sumSeries (smallest, largest) {
// The formulate to sum a series of integers is
// n * (max + min) / 2, where n is the length of the series.
var n = (largest - smallest + 1);
var sum = n * (smallest + largest) / 2; // note integer division
return sum;
}
var sum = sumSeries(min, max);
console.log(sum);
The sum of the first n integers (1 to n, inclusive) is given by the formula n(n+1)/2. This is also the nth triangular number.
S1 = 1 + 2 + ... + (a-1) + a + (a+1) + ... + (b-1) + b
= b(b+1)/2
S2 = 1 + 2 + ... + (a-1)
= (a-1)a/2
S1 - S2 = a + (a+1) + ... + (b-1) + b
= (b(b+1)-a(a-1))/2
Now we have a general formula for calculating the sum. This will be much more efficient if we are summing a large range (e.g. 1 million to 2 million).
Here is a one liner recursive program solution of SumAll using es6.
const SumAll = (num, sum = 0) => num - 1 > 0 ? SumAll(num-1,sum += num) : sum+num;
console.log(SumAll(10));
Note :: Although the best Example is using the Algorithm, as mentioned above.
However if the above can be improved.
function sum() {
a = Number(document.getElementById("rate_ts").value);
b = Number(document.getElementById("discount").value);
c = a - (Number(a) * Number(b) / 100);
d = Number(document.getElementById("ocharge").value) + c + Number(document.getElementById("pay_amt").value);
tax = (Number(a) * Number(12.36) / 100);
e = tax + d;
document.getElementById("net_amt").value = e;
}
this code is not working right......i want to add tax and for that i have given 12.36 but it is not returning anything..plz help
parseFloat()
Summary
The parseFloat() function parses a string argument and returns a
floating point number.
$('#three').click(function (e) {
a = parseFloat(document.getElementById("rate_ts").value);
b = parseFloat(document.getElementById("discount").value);
console.log(a+' | '+b);
});
WORKING DEMO
Try This,
function sum() {
a = parseFloat(document.getElementById("rate_ts").value);
b = parseFloat(document.getElementById("discount").value);
c = a - (a * b / 100);
d = parseFloat(document.getElementById("ocharge").value) + c + parseFloat(document.getElementById("pay_amt").value);
tax = a * 12.36 / 100;
e = tax + d;
document.getElementById("net_amt").value = e.toFixed(2);
}
If you want only two decimal point value then use number.toFixed(2)
Working Example
How can i prevent to javascript interpret my numeric vars from string vars?
var a = 100;
var b = -10
var c = a + b // 10-10 (string)
lets say i allways want
var c = a + b = 100+(-10) = 90 (number)
In your example c will always be 90, however;
var a = 100;
var b = "-10";
var c = a + b // "100-10" (string)
to prevent this convert the string to an integer;
var c = a + parseInt(b, 10);
or with a unary+
var c = a + +b;
Your code example...
var a = 100;
var b = -10
var c = a + b // 90 (number)
...won't do that unless one of the operands is a String. In your example, both are Number.
If you do have numbers inside of Strings, you can use parseInt() (don't forget to pass the radix of 10 if working in decimal) or possibly just prefix the String with + to coerce it to Number.
Your code works fine. See here.
JavaScript will always do the latter, as long as both of the variables you are adding are numbers.
The most concise way is prepending a + if you aren't certain whether the variables are numbers or strings:
var a = "100";
var b = "-10";
var c = +a + +b; // 90
This works since +"123" === 123 etc.