Skip to content

Instantly share code, notes, and snippets.

@assadvirgo
Created February 3, 2021 13:14
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 assadvirgo/a4bb3ce50f1f085fa60b033f35fb4362 to your computer and use it in GitHub Desktop.
Save assadvirgo/a4bb3ce50f1f085fa60b033f35fb4362 to your computer and use it in GitHub Desktop.
Simple Math Util Functions to Solve Floating Point Problems
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