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

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) {

// 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 {

Please enter a correct decimal value


A working example can be found here :

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

2018 All rights reserved | Powered by WordPress
Back to top
Theme by