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:
// 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<num:i<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=‘ = <strong>’+fr+‘</strong><small style=\’color:maroon\’> ‘+num2+‘/’+den2+‘</small></div>’;
}
// Ouput the result to a div of id ‘result’
document.getElementById(‘result’).innerHTML=+n+‘ = <strong>’+num+‘/’+den+‘</strong>’+more;
}
else {
document.getElementById(‘result’).innerHTML=‘<div class=\’error\’>Please enter a correct decimal value</div>’;
}
}
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











