i'm working on "toy problem" supposed write javascript function converts decimal fraction , returns string. example: fractionconverter(2.75) should return "11/4".
here code:
function fractionconverter (number) { if (number > 0) { var isnegative = false; } else if (number < 0) { var isnegative = true; } number = math.abs(number); if (number % 1 === 0) { var finalfrac = number + "/1"; } else { (var = 2; < 10000000000; i++) { if ((i * number) % 1 === 0) { var finalfrac = (i * number) + "/" + i; } if (finalfrac) { break; } } } var getfrac = function(numstring, bool) { if (!bool) { return numstring; } else { return "-" + numstring; } } return getfrac(finalfrac, isnegative); }
sorry formatting. anyway, i'm getting weird spec failure. function returns correct values following numbers: 0.5, 3, 2.5, 2.75, -1.75 , .88. reason, however, failing on 0.253213. returning 1266065/5000000 instead of 253213/1000000. not sure why.
thanks
javascript doesn't deal floating point numbers accurately.
i tried typing node:
0.253213 * 1000000
and got this:
253213.00000000003
here different approach testing multiplier
var bignumber = math.pow(10,8); var isdivisible = (math.round(i * number * bignumber)/bignumber % 1) == 0;
this of way.
this work way might expect to, if wanted 0.333333333 treated 1/3.
one issue highest integer can have javascript between 10^15 , 10^16.
if ((number * bignumber) > 2^53) not work.
Comments
Post a Comment