Code of the Day: Javascript Decimal To Fraction


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

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

(Page view Count: 145)

Published by

Larry Battle

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