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.
The following is an example of the function in use:
HTML Code:
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">
alert("abc".splitAt(2)[0])//alerts ab
alert("abc".splitAt(2)[1])//alerts c
</SCRIPT>
The way the function works:
The function always returns an Array with a length of 2 elements.
The given argument is the maxium string-length to allow for the the first element.
The second element is the remaining string that gets cut-off by the first element.
It looks like when you made your splitAt function, you were thinging of the split function.
When I made my function, I was think about how to split a string into two parts and return the two w/o losing any part of the string.
I needed to send a multi dimensional array to function through setTimeout, however this lost the internal structure of it so I created this that would turn it into a string that calling eval() would reconstruct it, and setTimeout is kind of like eval():
Code:
Array.prototype.toSource=function(){
var L=this.length,s='[',t,i;
for (i=0; i<L; i++) {
if (i>0) s+=',';
if (this[i].constructor==Array) s+=this[i].toSource();
else switch (typeof this[i]) {
case "number" : s+=this[i]; break;
case "boolean" : s+=this[i]; break;
default : s+='"'+this[i].toString().split('"').join('\\"')+'"';
}
}
return s+']';
}
Bookmarks