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'
or number 1.5
function ratio(fraction) {
var fraction = (fraction !== undefined) ? fraction : '1/1',
decimal = ??????????;
return decimal;
});
Is there a way to do this?
Something like this:
Function (ES6):
Function (ES6, condensed):
Examples:
Since no one has mentioned it yet there is a quick and dirty solution:
Which has the perks of correctly evaluating all sorts of mathematical strings.
People here will be quick to mention the dangers of using a raw eval but I submit this as the lazy mans answer.
I created a nice function to do just that, everything was based off of this question and answers but it will take the string and output the decimal value but will also output whole numbers as well with out errors
https://gist.github.com/drifterz28/6971440
Here is the bare bones minimal code needed to do this:
JsFiddle: http://jsfiddle.net/XS4VE/
Things to consider:
If you want to use the result as a fraction and not just get the answer from the string, a library like https://github.com/infusion/Fraction.js would do the job quite well.