Skip to content

Instantly share code, notes, and snippets.

@shimondoodkin
Created August 26, 2017 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shimondoodkin/dcd16b56492776d70ff510a6af6d0d12 to your computer and use it in GitHub Desktop.
Save shimondoodkin/dcd16b56492776d70ff510a6af6d0d12 to your computer and use it in GitHub Desktop.
//simple and correct math for money arithmetics
Number.prototype.add=function(a){ return parseFloat((this+a).toFixed(15)) };
Number.prototype.sub=function(a){ return parseFloat((this-a).toFixed(15)) };
Number.prototype.mul=function(a){ return parseFloat((this*a).toFixed(15)) };
Number.prototype.div=function(a){ return parseFloat((this/a).toFixed(15)) };
// use with one number each time.
// > 0.1.add(0.1).add(0.1).mul(10).div(10)
// 0.3
//
// > 0.1.add(0.2)
// 0.3 // correct result
//
// 0.1+0.2
// 0.30000000000000004
// incorrect result (correct up to 15 decimal points,
// due to iee 754 floating point encoding and decoding of the stored number in memory,
// theoretically, it is correct. but for real use it isn't. )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment