Your way of figuring out the fraction is definitely better. I just pulled that other one out of my @$$, although it's aiming for the same "something/999" kind of thing.
Here's what I mean about marking up the string. I tell the function which part of the decimal repeats by putting it in square brackets
Code:
String.prototype.toRational=function() {
var a=this.substring(0, this.indexOf("."));
var b=this.substring(this.indexOf(".")+1, this.indexOf("["));
var c=this.substring(this.indexOf("[")+1, this.indexOf("]"));
var lena=a.length;
var lenb=b.length;
var lenc=c.length;
var x=parseInt(a+b);
var y=parseInt(a+b+c);
var z=y-x;
var den="";
for(var i=0; i<lenc; i++) den+="9";
for(var i=0; i<lenb; i++) den+="0";
return z+"/"+den+"="+z/parseInt(den);
}
document.write("5.1[42857]".toRational());
Kids, kids... you tried your best, and you failed miserably; the lesson is: never try.
Bookmarks