Convert Fraction String to Decimal?

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

提交回复
热议问题