Code of the Day: Javascript Decimal To Fraction

Source: mivk from StackOverflow.com
Code

/**
@function dec2frac
@returns string
@purpose Convert a decimal to a fraction
*/
function dec2frac(d) {
    var df = 1, top = 1, bot = 1;
    var limit = 1e5; //Increase the limit to get more precision.
  
    while (df != d && limit-- > 0) {
        if (df < d) {
            top += 1;
        }
        else {
            bot += 1;
            top = parseInt(d * bot, 10);
        }
        df = top / bot;
    }
    return top + '/' + bot;
}

Demo
JSBIN link

Example Output
dec2frac ( 0.1) returns "1/10"
dec2frac ( 0.2) returns "1/5"
dec2frac ( 0.5) returns "1/2"
dec2frac ( 0.9999) returns "9999/10000"
dec2frac ( 0.75) returns "3/4"
dec2frac ( 2.718281828459045) returns "135915/50000", but this evaluates to 2.7183
dec2frac ( 3.141592653589793) returns "157079/50000", but this evaluates to 3.14158

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

Share
Published by
Larry Battle

Recent Posts

What really is Data Science? Told by a Data Scientist

What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

7 years ago

Video: How Water Towers Work

How Water Towers Work - Practical Engineering

7 years ago

Dev Tip: Simple tips to improve code reviews

Writing perfect code is a challenging process. That's where code reviews come in to help…

7 years ago

Video: How AI will change the 3d industry

"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

7 years ago

Best Software Presentation for 2018

"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

7 years ago

Dev Video: A Few Linux Shell Tips

My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

7 years ago