Convert Fraction String to Decimal?

前端 未结 16 659
谎友^
谎友^ 2020-12-05 13:55

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\'

16条回答
  •  星月不相逢
    2020-12-05 14:40

    I created a nice function to do just that, everything was based off of this question and answers but it will take the string and output the decimal value but will also output whole numbers as well with out errors

    https://gist.github.com/drifterz28/6971440

    function toDeci(fraction) {
        fraction = fraction.toString();
        var result,wholeNum=0, frac, deci=0;
        if(fraction.search('/') >=0){
            if(fraction.search('-') >=0){
                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;
    }
    
    /* Testing values / examples */
    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.2"));
    

提交回复
热议问题