0

When I try to add a decimal value with an integer, I am getting a wrong answer.

Here's what I am doing: I am getting 4 numbers from a string like the following: 8' 9'' X 7' 4'' into 4 variables: v1, v2, v3, v4

Then I am dividing the 2nd and 4th numbers v2, v4 by 12 (to convert inches to feet in decimal) and saving them into two more variables v5, v6

So,

v5 = v2/12; // 9/12 = 0.75
v6 = v4/12; // 4/12 = 0.33

Everything is working fine till here, and it is giving the correct results. Then, when I try to add v1+v5, and v2+v6, I am getting a wrong answer.

v7 = v1+v5 // 8+0.75 should be 8.75; but I am getting 80.75
v8 = v2+v6 // 7+0.33 should be 7.33; but I am getting 70.33

2 Answers 2

5

You are just merging the two variable is Not performing a addition .so you need parse the variable using parseFloat() .They convert string to number

v7 = parseFloat(v1)+parseFloat(v5)
v8 = parseFloat(v2)+parseFloat(v6)

Working example

v1 = "8"
v2 = "7"
v5 = "0.75"
v6 = "0.33"
v7 = parseFloat(v1) + parseFloat(v5)
v8 = parseFloat(v2) + parseFloat(v6)

console.log(v7,v8)

Sign up to request clarification or add additional context in comments.

1 Comment

v5 and v6 are numbers, not strings since string÷number gives a number. parseInt(v1) + v5 or +v1 + v5 is sufficient.
1

You have a problem with the type of your variable. You could try to parseInt() / parseFloat them.

v7 = parseFloat(v1) + parseFloat(v5)

2 Comments

No, don't use eval.
@RobG removed from my answer.

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.