Convert Fraction String to Decimal?

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

    Too late, but can be helpful:

    You can use Array.prototype.reduce instead of eval https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

    ES6

    const fractionStrToDecimal = str => str.split('/').reduce((p, c) => p / c);
    console.log(fractionStrToDecimal('1/4/2')); // Logs 0.125
    console.log(fractionStrToDecimal('3/2')); // Logs 1.5
    

    CJS

    function fractionStrToDecimal(str) {
      return str.split('/').reduce((p, c) => p / c);
    }
    console.log(fractionStrToDecimal('1/4')); // Logs 0.25
    

    [EDIT] Removed reducer initial value and now the function works for numerators greater than 1. Thanks, James Furey.

    0 讨论(0)
  • 2020-12-05 14:34

    I have a function I use to handle integers, mixed fractions (including unicode vulgar fraction characters), and decimals. Probably needs some polishing but it works for my purpose (recipe ingredient list parsing).

    • NPM
    • GitHub

    Inputs "2 1/2", "2½", "2 ½", and "2.5" will all return 2.5. Examples:

    var numQty = require("numeric-quantity");
    
    numQty("1 1/4") === 1.25;  // true
    numQty("3 / 4") === 0.75;  // true
    numQty("¼" ) === 0.25;     // true
    numQty("2½") === 2.5;      // true
    numQty("¾") === 0.75;      // true
    numQty("⅓") === 0.333;     // true
    numQty("⅔") === 0.667;     // true
    

    One thing it doesn't handle is decimals within the fraction, e.g. "2.5 / 5".

    0 讨论(0)
  • 2020-12-05 14:34

    safer eval() according to MDN

    const safeEval = (str) => {
       return Function('"use strict";return (' + str + ")")();
    }
    
    safeEval("1 1/2") // 1.5
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Do_not_ever_use_eval!

    0 讨论(0)
  • 2020-12-05 14:37

    Also a bit late to the party, but an alternative to eval() with less security issues (according to MDN at least) is the Function() factory.

    var fraction = "3/2";
    console.log( Function("return (" + fraction + ");")() );
    

    This would output the result "1.5" in the console.

    Also as a side note: Mixed fractions like 1 1/2 will not work with neither eval() nor the solution with Function() as written as they both stumble on the space.

    0 讨论(0)
  • 2020-12-05 14:38

    To convert a fraction to a decimal, just divide the top number by the bottom number. 5 divided by 3 would be 5/3 or 1.67. Much like:

    function decimal(top,bottom) {
        return (top/bottom)
    }
    

    Hope this helps, haha

    0 讨论(0)
  • 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"));
    
    0 讨论(0)
提交回复
热议问题