Created
September 28, 2017 07:44
-
-
Save ethaizone/e33eef2981f0efe35622f7418e9ba379 to your computer and use it in GitHub Desktop.
Example how to make math calculation with safe output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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