Javascript function to convert decimal to fraction

A while back, while developing a small scientific calculator-like widget, I needed a function to convert a decimal value into a proper fraction form. After a lot of thinking and trial and errors, I came up with this little piece of code that worked quite well.

Here is the javascript code:

[code lang=”javascript”]
function dec2frac(){
// Read the value from a text input element of id ‘n’
var n=document.getElementById(‘n’).value;
// Check if the value is a number
if(!isNaN(n) && n!==” && n!==’0′ && n!==’Infinity’ && n!==’-Infinity’)
{
// to count the number of decimal places
var dn=n.substr(n.lastIndexOf(‘.’));
var nd=dn.length-1;
var den=1,i;

// Prepare an appropriate denominator
for(i=1;i<=nd;i++)
den*=10

var num=Math.floor(n*den);

// This is the heart of the function
// Successively check for common factors of numerator and denominator
// Divide if a common factor is found
for(i=2;num>den?i if(num%i==0 && den%i==0) {
den/=i;
num/=i;
i=1;
}
}

// This part prepares the mixed fraction form
var num2=num%den;
var den2=den;
var fr=(num-num2)/den;
var more='';
if(fr!==0) {
more=' = ‘+fr+’ ‘+num2+’/’+den2+’

‘;
}
// Ouput the result to a div of id ‘result’
document.getElementById(‘result’).innerHTML=+n+’ = ‘+num+’/’+den+’‘+more;
}
else {
document.getElementById(‘result’).innerHTML=’

Please enter a correct decimal value

‘;
}
}
[/code]

A working example can be found here : http://www.dynamicguru.com/dec2frac.html

The code can easily be ported to other programming languages such as C/C++ , Java, VB or php