Convert Fraction String to Decimal?

前端 未结 16 643
谎友^
谎友^ 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:46

    From a readability, step through debugging perspective, this may be easier to follow:

    // i.e. '1/2' -> .5
    // Invalid input returns 0 so impact on upstream callers are less likely to be impacted
    function fractionToNumber(fraction = '') {
        const fractionParts = fraction.split('/');
        const numerator = fractionParts[0] || '0';
        const denominator = fractionParts[1] || '1';
        const radix = 10;
        const number = parseInt(numerator, radix) / parseInt(denominator, radix);
        const result = number || 0;
    
        return result;
    }
    

提交回复
热议问题