Convert Fraction String to Decimal?

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

    If you don't mind using an external library, math.js offers some useful functions to convert fractions to decimals as well as perform fractional number arithmetic.

    console.log(math.number(math.fraction("1/3"))); //returns 0.3333333333333333
    console.log(math.fraction("1/3") * 9) //returns 3
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.20.1/math.js"></script>

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

    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.

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

    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"
    
    0 讨论(0)
  • 2020-12-05 14:53

    This too will work:

    let y = "2.9/59"
    let a = y.split('')
    let b = a.splice(a.indexOf("/"))
    console.log(parseFloat(a.join('')))
    a = parseFloat(a.join(''))
    console.log(b)
    let c = parseFloat(b.slice(1).join(''))
    let d = a/c
    console.log(d) // Answer for y fraction
    
    0 讨论(0)
提交回复
热议问题