# Don't understand what's wrong

I have the following code:

``````  kg.value = ((lb.value / 14) + st.value) * 6.35029318;
console.log(st.value);
console.log(lb.value);
console.log(kg.value);
``````

Which produces the following results:

``````2
1
0.45359237
``````

The kg value would only be right if the st value was zero. I know I fewer marbles than I used to have but I can’t see what’s wrong here.

This code is not enough to understand the problem.

This works absolutely right. So maybe you have a race condition or a validation on some object attribute or the a setter that is manipulating the value?

Ah, okay. I thought that would suffice. Here’s a codepen:

Just to be clear, with st = 2 and lb = 1, I expected kg to be 13.154.

It’s much more simple than that.

By comparison, when the printer doesn’t work first check that the cable is plugged in and getting power, before attempting more complicated things such as diagnosing circuit boards.

The string values should be converted to numbers. That way addition will add numbers, instead of concatenating strings.

``````  const stField = document.querySelector("#st");
const lbField = document.querySelector("#lb");
const kgField = document.querySelector("#kg");
const st = Number(stField.value);
const lb = Number(lbField.value);
kgField.value = ((lb / 14) + st) * 6.35029318;
console.log(stField.value);
console.log(lbField.value);
console.log(kgField.value);
``````

Here’s a slightly improved version extracting out the calculations:

``````  const stField = document.querySelector("#st");
const lbField = document.querySelector("#lb");
const kgField = document.querySelector("#kg");

function poundsToStones(lb) {
return lb / 14;
}
function stonesToKilos(st, lb) {
st += poundsToStones(lb);
return st * 6.35029318;
}
const st = Number(stField.value);
const lb = Number(lbField.value);
kgField.value = stonesToKilos(st, lb);

console.log(stField.value);
console.log(lbField.value);
console.log(kgField.value);
``````
4 Likes

Thank you, @Paul_Wilkins. I’ll let myself out.

4 Likes

I count myself to be in your same company for I didn’t even think of it at first, having to log out
`((lb / 14) + st)` before even thinking of that solution.

2 Likes

To be honest, I hadn’t thought that Gandalf the wise has made such an easy mistake

4 Likes

In my defence, I’m more used to PHP which uses different symbols for addition and concatenation, but yes, it was a rooky mistake. :sigh:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.