Search code examples
javascripttype-conversiondecimalevalfractions

Javascript - convert mixed fraction to decimal


I have a series of recipe ingredients listed like "1-1/2" which I need to change to a proper number like "1.5" in order to calculate according to serving sizes. How do I change the mixed fraction to a decimal number? I've seen the eval function, which works for things like "1/2", but for something like "1-1/2" it evaluates it as ".5".

Thanks for your help!


Solution

  • Note: Add your safety checks (like ensuring there is a "-" in the input etc.)

    Code:

    function toDecimal(_x) {
       var parts = _x.split("-");
       var decParts = parts[1].split("/");
       return parseInt(parts[0], 10) + 
                 (parseInt(decParts[0], 10) / parseInt(decParts[1], 10));
    }
    var x = "1-1/2";
    console.log(toDecimal(x));