Feedback Form

Friday, March 14, 2008

Decimal To Fraction

Change from decimal to fraction using javascript:

I got a sample after searching on google and found a good sample, i can't remember the website link, but i tried it in a website and it worked fine with me.

Number.prototype.fraction=fraction;
function fraction(item){
if(item.value != "" && item.value.indexOf(".")!=-1 && item.value.indexOf("/")==-1)
{
decimal=item.value
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;
}
}
item.value= ((whole==0)?"" : whole+" ")+decimal+"/"+num;
}
}


kick it on DotNetKicks.com

0 comments: