Skip to content

Instantly share code, notes, and snippets.

@ethaizone
Created September 28, 2017 07:44
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 ethaizone/e33eef2981f0efe35622f7418e9ba379 to your computer and use it in GitHub Desktop.
Save ethaizone/e33eef2981f0efe35622f7418e9ba379 to your computer and use it in GitHub Desktop.
Example how to make math calculation with safe output
const countDecimals = function (value) {
if(Math.floor(value) === value) return 0;
return value.toString().split(".")[1].length || 0;
}
const operators = {
'+': (a, b) => {
let decimalLength = Math.pow(10, Math.max(countDecimals(a), countDecimals(b)))
return ((a*decimalLength) + (b*decimalLength))/decimalLength
},
'-': (a, b) => {
let decimalLength = Math.pow(10, Math.max(countDecimals(a), countDecimals(b)))
return ((a*decimalLength) - (b*decimalLength))/decimalLength
},
'*': (a, b) => {
let decimalLength = Math.pow(10, Math.max(countDecimals(a), countDecimals(b)))
return ((a*decimalLength) * (b*decimalLength))
},
'/': (a, b) => {
let decimalLength = Math.pow(10, Math.max(countDecimals(a), countDecimals(b)))
return ((a*decimalLength) / (b*decimalLength))
},
'%': (a, b) => {
let decimalLength = Math.pow(10, Math.max(countDecimals(a), countDecimals(b)))
return ((a*decimalLength) % (b*decimalLength))
},
}
//Example
// 0.1+0.2 = 0.30000000000000004
// With this you will get 0.3
console.log(operators['+'](0.1, 0.2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment