I'm using this code to convert decimals to a fraction:
Number.prototype.fraction=fraction;
function fraction(decimal){
if(!decimal){
decimal=this;
}
whole = String(decimal).split('.')[0];
decimal = parseFloat("."+String(decimal).split('.')[1]);
num = "1";
for(z=0; z<String(decimal).length-2; z++){
num += "0";
}
decimal = parseInt(decimal*num);
num = parseInt(num);
for(z=2; z<decimal+1; z++){
if(decimal%z==0 && num%z==0){
decimal = decimal/z;
num = num/z;
z=2;
}
}
return ((whole==0)?"" : whole+" ")+decimal+"/"+num;
}
This works, but has some issues that I can't seem to resolve. First, numbers with long (or endless) digits after the decimal kill the page so I've had to manually limit the input using .round()
before utilizing it. Second, I need to be able to round the fraction value to the nearest 16th.
I realize this is an especially tricky problem, as I've discovered while trolling around Google for two days, but hopefully someone knows how to do it. I'm open to any solutions.
Try:
Math.round( number * 16) / 16
For example:
Math.round(32578.8252789345798345987683476983476908347569873490867309487609875690860*16)/16
gives
32578.8125
Which is = 32578 + 13/16