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?
Asked
Active
Viewed 243 times
0
-
1`eval("2/4")` (oh...) – Yeldar Kurmangaliyev Dec 10 '15 at 06:23
-
Dude!! Seriously extremely thanks for that quick reply!!! So, can i use this to change the result obtained from regexp? I guss i can.. – Mrityunjay Bhardwaj Dec 10 '15 at 06:23
-
@Tushar this does not work. It parses only the first part of the string. `parseFloat("5/4")` returns 5. – Ortiga Dec 10 '15 at 06:23
-
@Mrityunjay Bhardwaj: Is it always a fraction? – zerkms Dec 10 '15 at 06:24
6 Answers
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
-
Don't need to cast, `/` will cast it implicitly `ssplit[0] / ssplit[1]` – Tushar Dec 10 '15 at 06:29
-
1
function myFunction() {
var str = "3/4";
var res = str.split("/");
alert(parseFloat(res[0]/res[1]));
}

solanki dev
- 27
- 8
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