Created
February 3, 2021 13:14
-
-
Save assadvirgo/a4bb3ce50f1f085fa60b033f35fb4362 to your computer and use it in GitHub Desktop.
Simple Math Util Functions to Solve Floating Point Problems
This file contains 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 toInt = (n) => { | |
// If n is not a number return n | |
if ( typeof n != 'number') return n; | |
let s = n.toString(); | |
// If n is a whole number return n | |
if (s.indexOf('.') == -1) return n; | |
// If n is a floating number return the int representation | |
let len = s.split('.')[1].length; | |
for (let i = 1; i <=len; i++) { | |
n = n * 10; | |
} | |
return n; | |
} | |
const toFloat = (n, d) => { | |
// If n is not a number return n | |
if ( typeof n != 'number' || typeof d != 'number') return n; | |
let s = n.toString(); | |
for (let i = 1; i <= d; i++) { | |
n = n / 10; | |
} | |
return n; | |
} | |
/* ====== Usage ======= | |
TO Solve the Problem of | |
0.1 + 0.2 = 0.3000000000004 | |
let x = 0.1 | |
let y = 0.2 | |
let z = toFloat(toInt(x) + toInt(y), 1); | |
z = 0.3; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment