Sorry for this basic JS question.
I have this code:
const value0 = parseInt(this.value0); // 8500 const value1 = parseInt(this.value1); // 3.5 const value2 = parseInt(this.value2); // 5700 const value3 = parseInt(this.value3); // 0.3 const valueExtra = parseInt(this.valueExtra); // 10.5 let myResult = 0 if (value0 > (value1 * value2)) { myResult = (value1 * value2) * value3; } else { myResult = valueExtra * value3; } return ( myResult )
my value is always 0.
I know it’s because let is not changing, but I don’t know why.
Could you help me, please?
Advertisement
Answer
parseInt('0.3')
is 0. So one of your values is 0, so the result will always be 0. Try using parseFloat
instead.
const value0 = parseInt(`8500`); const value1 = parseInt(`3.5`); const value2 = parseInt(`5700`); const value3 = parseInt(`0.3`); const valueExtra = 1; console.log(`values check: ${[value0, value1, value2, value3]}`); let myResult = 0; if (value0 > (value1 * value2)) { myResult = (value1 * value2) * value3; console.log(`parseInt: value0 > (value1 * value2)=> ${myResult}`); } else { myResult = valueExtra * value3; console.log(`parseInt: else => ${myResult}`); } // use parseFloat const [v0, v1, v2, v3, vE] = [ parseFloat(`8500`), parseFloat(`3.5`), parseFloat(`5700`), parseFloat(`0.3`), 1 ]; console.log(`values check: ${[v0, v1, v2, v3]}`); if (v0 > (v1 * v2)) { myResult = (v1 * v2) * v3; console.log(`parseFloat: v0 > (v1 * v2)=> ${myResult}`); } else { myResult = vE * v3; console.log(`parseFloat: else => ${myResult}`); }