drifterz28
10/14/2013 - 6:04 AM

Fractions to Decimals function, needs to be able to have hole numbers and floats entered in as well as fractions

Fractions to Decimals function, needs to be able to have hole numbers and floats entered in as well as fractions

function toDeci(fraction) {
    var result, wholeNum = 0, frac, deci = 0;
    if(fraction.search('/') >= 0){
        if(fraction.search('-') >= 0){
            var wholeNum = fraction.split('-');
            frac = wholeNum[1];
            wholeNum = parseInt(wholeNum, 10);
        }else{
            frac = fraction;
        }
        if(fraction.search('/') >=0){
            frac =  frac.split('/');
            deci = parseInt(frac[0], 10) / parseInt(frac[1], 10);
        }
        result = wholeNum + deci;
    }else{
        result = +fraction;
    }
    return result.toFixed(2);
}

console.log('1 ',toDeci("1-7/16"));
console.log('2 ',toDeci("5/8"));
console.log('3 ',toDeci("3-3/16"));
console.log('4 ',toDeci("12"));
console.log('5 ',toDeci("12.20"));
console.log('5 ',toDeci("1"));