Search code examples
javascriptscopefractions

Convert Fraction String to Decimal?


I'm trying to create a javascript function that can take a fraction input string such as '3/2' and convert it to decimal—either as a string '1.5' or number 1.5

function ratio(fraction) {
    var fraction = (fraction !== undefined) ? fraction : '1/1',
    decimal = ??????????;
    return decimal;
});

Is there a way to do this?


Solution

  • Since no one has mentioned it yet there is a quick and dirty solution:

    var decimal = eval(fraction); 
    

    Which has the perks of correctly evaluating all sorts of mathematical strings.

    eval("3/2")    // 1.5
    eval("6")      // 6
    eval("6.5/.5") // 13, works with decimals (floats)
    eval("12 + 3") // 15, you can add subtract and multiply too
    

    People here will be quick to mention the dangers of using a raw eval but I submit this as the lazy mans answer.