0

Hey guys i want to extract/evaluate the answer 2/4 in a string even ehen doing Number ("2/4") it gives me NaN as a result which is fairly reasonable! So my question is how can i evaluate this fraction from a string?

6 Answers6

3

You can do eval("2/4"), which will properly result in 0.5.
However, using eval is a really bad idea...

If you always have a fraction in format A/B, you can split it up and compute:

var s = "11/47";
var ssplit = s.split('/');

document.body.innerText = ssplit[0] / ssplit[1];

Note that Division operator / will implicitly cast strings "11" and "47" to 11 and 47 Numbers.

Tushar
  • 85,780
  • 21
  • 159
  • 179
Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
2

You are looking for eval. Note

parseFloat("2/4")
2
parseFloat("4/2")
4
eval("4/2")
2
eval("2/4")
0.5
dnit13
  • 2,478
  • 18
  • 35
1
 function myFunction() {
       var str = "3/4";
     var res = str.split("/");
    alert(parseFloat(res[0]/res[1]));
 }
0

Try with eval function :

eval("2/4");
0
(function(str){
    var numbers = str.split("/").map(Number);
    return numbers[0] / numbers[1]; 
})("2/4")

Keep in mind this does not check for invalid input.

Ortiga
  • 8,455
  • 5
  • 42
  • 71
0

Parsing the string only valid for numbers like 0-10 and a decimal (.) and all other if included will then result in NaN.

So, what you can do is like this:

Number(2/4)//0.5
parseFloat(2/4)//0.5
Number('2')/Number('4');//0.5
parseFloat('2')/parseFloat('4');//0.5
Number('2/4');//NaN as / is not parsable string for number
parseFloat('2/4');//2 as upto valid parsable string
parseFloat('1234/4');//1234

So, you can split string then use that like @Yeldar Kurmangaliyev answered for you.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231