Calculating a fraction from a double in javascript
The following code will allow you to calculate a fraction in javascript
function getFraction(dblValue, dblTolerance) { var f0 = 1 / dblValue; var f1 = 1 / (f0 - Math.floor(f0)); var a_t = Math.floor(f0); var a_r = Math.round(f0); var b_t = Math.floor(f1); var b_r = Math.round(f1); var c = Math.round(1 / (f1 - Math.floor(f1))); if (Math.abs(1.0 / a_r - dblValue) <= dblTolerance) { return [1, a_r]; } else if (Math.abs(b_r / (a_t * b_r + 1.0) - dblValue) <= dblTolerance) { return [b_r, a_t * b_r + 1]; } else { return [c * b_t + 1, c * a_t * b_t + a_t + c]; } }
For example the following code examples give you a numerator and a denominator
console.log(getFraction(0.75,0.02)); /*[3, 4]*/ /***********************************/ console.log(getFraction(0.5,0.02)); /*[1, 2]*/ /***********************************/ console.log(getFraction(0.25,0.02)); /*[1, 4]*/ /***********************************/ console.log(getFraction(0.33,0.02)); /*[1, 3]*/ /***********************************/
Hope that's of use to somebody!