Convert Fraction String to Decimal?

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

提交回复
热议问题