Last active
June 26, 2026 19:03
-
-
Save jt3k/1870464a53929847a88e2da9c0f48ee4 to your computer and use it in GitHub Desktop.
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
| 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 |
zemnuhovanadezda9-jpg
commented
Jun 26, 2026
<script src="https://gist.github.com/jt3k/3cd0cb9bf3250dbda261.js"></script>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment