Convert Fraction String to Decimal?

2019-01-18 02:38发布

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' or number 1.5

function ratio(fraction) {
    var fraction = (fraction !== undefined) ? fraction : '1/1',
    decimal = ??????????;
    return decimal;
});

Is there a way to do this?

12条回答
Emotional °昔
2楼-- · 2019-01-18 03:12

Something like this:

bits = fraction.split("/");
return parseInt(bits[0],10)/parseInt(bits[1],10);
查看更多
forever°为你锁心
3楼-- · 2019-01-18 03:13

Function (ES6):

function fractionToDecimal(fraction) {
  return fraction
    .split('/')
    .reduce((numerator, denominator, i) =>
      numerator / (i ? denominator : 1)
    );
}

Function (ES6, condensed):

function fractionToDecimal(f) {
  return f.split('/').reduce((n, d, i) => n / (i ? d : 1));
}

Examples:

fractionToDecimal('1/2');     // 0.5
fractionToDecimal('5/2');     // 2.5
fractionToDecimal('1/2/2');   // 0.25
fractionToDecimal('10/5/10'); // 0.2
fractionToDecimal('0/1');     // 0
fractionToDecimal('1/0');     // Infinity
fractionToDecimal('cat/dog'); // NaN
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-18 03:18

Since no one has mentioned it yet there is a quick and dirty solution:

var decimal = eval(fraction); 

Which has the perks of correctly evaluating all sorts of mathematical strings.

eval("3/2")    // 1.5
eval("6")      // 6
eval("6.5/.5") // 13, works with decimals (floats)
eval("12 + 3") // 15, you can add subtract and multiply too

People here will be quick to mention the dangers of using a raw eval but I submit this as the lazy mans answer.

查看更多
对你真心纯属浪费
5楼-- · 2019-01-18 03:19

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"));
查看更多
Summer. ? 凉城
6楼-- · 2019-01-18 03:20

Here is the bare bones minimal code needed to do this:

var a = "3/2";
var split = a.split('/');
var result = parseInt(split[0], 10) / parseInt(split[1], 10);
alert(result); // alerts 1.5

JsFiddle: http://jsfiddle.net/XS4VE/

Things to consider:

  • division by zero
  • if the user gives you an integer instead of a fraction, or any other invalid input
  • rounding issues (like 1/3 for example)
查看更多
Juvenile、少年°
7楼-- · 2019-01-18 03:26

If you want to use the result as a fraction and not just get the answer from the string, a library like https://github.com/infusion/Fraction.js would do the job quite well.

var f = new Fraction("3/2");
console.log(f.toString()); // Returns string "1.5"
console.log(f.valueOf()); // Returns number 1.5

var g = new Fraction(6.5).div(.5);
console.log(f.toString()); // Returns string "13"
查看更多
登录 后发表回答