Joppo
Joppo

Reputation: 729

error javascript code calculation

Pls consider the calculation in javascript code below. With example values:

...the console shows a strange result value 0200.00615.6. which I don't understand. I noticed the values 200.00 and 615.6, - the latter the result of investmentvar * nrofparts- in this result value. But I'd expect (and target to get) the result 815.6 (200+(123.12*5.00).

What goes wrong? Does this relate to a kind of format issue?

javascript code:

var result =0;

result += (investmentfix + (investmentvar * nrofparts));

console.log(result);

Upvotes: 0

Views: 77

Answers (1)

Jeff Noel
Jeff Noel

Reputation: 7618

Try the following:

result = parseFloat(0,10);
result+=parseFloat(investmendfix,10)+parseFloat(investmentvar*nrofparts,10);
console.log(result);

This ensures that the JavaScript engine parses the variables at numbers instead of strings.

parseFloat() syntax: parseFloat(myNumber,base);

Upvotes: 1

Related Questions