Bevels Bevels - 24 days ago 13
Javascript Question

Javascript / jQuery Math not adding up correctly?

I've hit a strange issue where my math isn't adding up, hope someone can help!

If I specify a value then everything works as expected. However if I grab values from variables, everything goes a little pear shaped?!?!

Example.

$('#mydiv').append(0.5);
results in 0.5 being appended to
#mydiv
- happy days!

However if I do the following...

var firstscore = 100;
var secondscore = 50;

jQuery('#mydiv').append(firstscore - secondscore / 100);


I end up with 99.5 ???

Does this have something to do with floating point math?

Anyone know how to fix it?

Answer

Try this:

jQuery('#mydiv').append((firstscore - secondscore) / 100);

This is because of Operator Associativity & Precedence.

Read this

Comments