Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Created April 18, 2013 14:38
Show Gist options
  • Select an option

  • Save bloodyowl/5413231 to your computer and use it in GitHub Desktop.

Select an option

Save bloodyowl/5413231 to your computer and use it in GitHub Desktop.
Float issues ?

If you have issues with JavaScript floats :

.1 + .2 
// 0.30000000000000004
.3 - .1
// 0.19999999999999998
.1 * .1
// 0.010000000000000002
Math.add(.1, .2)
// 0.3
Math.remove(.3, .1)
// 0.2
Math.times(.1, .1)
// 0.01
;(function(){
function makeCalculation(o){
return new Function('a', 'b', 'var c=a.toString(),d=b.toString(),r,s,dec=Math.pow(10,Math.max.call(Math,(r=c.indexOf("."))&&c.slice(r).length,(s=d.indexOf("."))&&d.slice(s).length));return((a*dec)'+o+'(b*dec))' + (o=="/"?"*":"/") + (o=="*"?'(dec*dec)':o=="/"?"(dec/dec)":'dec'))
}
Math.add = makeCalculation("+")
Math.remove = makeCalculation("-")
Math.times = makeCalculation("*")
Math.divide = makeCalculation("/")
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment