0

This is my function:

var ans=(X*X)/(Y+Z);

When I enter 10, 20, and 10 - respectively- the addition bit comes out as 2010 and not 30. How can I fix this?

2
  • 5
    Because you're adding strings. Commented May 24, 2013 at 2:30
  • where is your code which assigns X, Y and Z ? Commented May 24, 2013 at 2:31

1 Answer 1

4

Make sure to convert your strings to numbers first:

var X = "10";
var Y = "20";
var Z = "10";

X = +X; // unary plus operator converts to a number
Y = Number(Y); // or use the Number function
Z = parseInt(Z, 10); // or parseInt

var ans=(X*X)/(Y+Z);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.