Convert Fraction String to Decimal?

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

    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)

提交回复
热议问题