Convert Fraction String to Decimal?
Since no one has mentioned it yet there is a quick and dirty solution:
var decimal = eval(fraction);
Which has the perks of correctly evaluating all sorts of mathematical strings.
eval("3/2") // 1.5eval("6") // 6eval("6.5/.5") // 13, works with decimals (floats)eval("12 + 3") // 15, you can add subtract and multiply too
People here will be quick to mention the dangers of using a raw eval but I submit this as the lazy mans answer.
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)
Something like this:
bits = fraction.split("/");return parseInt(bits[0],10)/parseInt(bits[1],10);