coderD
coderD

Reputation: 265

Javascript: adding an integer and decimal giving wrong answer

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

Upvotes: 0

Views: 1171

Answers (2)

prasanth
prasanth

Reputation: 22500

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)

Upvotes: 5

Baldráni
Baldráni

Reputation: 5640

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

v7 = parseFloat(v1) + parseFloat(v5)

Upvotes: 1

Related Questions