开发者

How to avoid eval for string to decimal conversion

I have "1/7" and开发者_如何学运维 want to get decimal equivalent. Ofcourse I can use eval( "1/7"), but considering eval is evil, any other method?


eval is not evil. It's only evil to use it on arbitrary strings without checking your input.


You can write your own function, it's not really complicated and pretty efficient:

function ParseFloat(sFloat) {
    var parts = sFloat.split("/");
    if (parts.length == 2) {
        var first = parseInt(parts[0], 10);
        var second = parseInt(parts[1], 10);
        if (!isNaN(first) && !isNaN(second))
            return first / second;
    }
    return NaN;
}

Usage:

var s = "1/7";
alert(ParseFloat(s));

Live test case: http://jsfiddle.net/RK3zS/

Edit: if you're after working with such entities, I would use "class" for this for example:

function DecimalFraction(first, second) {
    this.first = first;
    this.second = second;
    this.toString = function() {
        return first / second;
    }
}

And then:

var s = new DecimalFraction(3, 7);
alert(s);

More elegant in my opinion. Updated jsFiddle.


That's the only option we have, I guess. Eval is not that evil too. Else create own function to identify values and do calculations.


Assuming you have to calculate decimals and only decimals:

txt = "1/7";

firstNumber = txt.subString(0, txt.indexOf('/'));
secondNumber = txt.subString(txt.indexOf('/') + 1, txt.length);

decml = fistNumber / secondNumber;


try it like this.

var txt = "1/7";
var result = new Function("return " + txt)()
console.log(result); // 0.14285714285714285
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜