Bevels Bevels - 1 year ago 90
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?!?!


results in 0.5 being appended to
- 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 Source

Try this:

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

This is because of Operator Associativity & Precedence.

Read this

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download