Skip to content

Instantly share code, notes, and snippets.

@jt3k
Last active January 16, 2017 15:58
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 jt3k/1870464a53929847a88e2da9c0f48ee4 to your computer and use it in GitHub Desktop.
Save jt3k/1870464a53929847a88e2da9c0f48ee4 to your computer and use it in GitHub Desktop.
function safeMath(example) {
const numbersRegX = /[0-9]+(\.[0-9]+|)?/g;
const replaceData = [];
example.replace(numbersRegX, function() {
replaceData.push(arguments);
});
const maxFract = replaceData.reduce((max, [,fract]) => {
if (fract && max < fract.length) {
max = fract.length;
}
return max;
}, 1);
const commonDelimer = `1${'0'.repeat(maxFract)}`;
const modifiedExample = example.replace(numbersRegX, function(match) {
return `(${match} * ${commonDelimer})`;
});
const result = eval(`(${modifiedExample})/${commonDelimer}`);
return result;
}
// example of use
safeMath('0.1 + 0.2'); // => 0.3
// bugs:
// 2*3
// 2/4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment