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?
If you don't mind using an external library, math.js offers some useful functions to convert fractions to decimals as well as perform fractional number arithmetic.
It works with eval() method but you can use parseFloat method. I think it is better! Unfortunately it will work only with that kind of values - "12.2" not with "5/8", but since you can handle with calculation I think this is good approach!
Too late, but can be helpful:
You can use
Array.prototype.reduce
instead ofeval
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceES6
CJS
[EDIT] Removed reducer initial value and now the function works for numerators greater than 1. Thanks, James Furey.
Also a bit late to the party, but an alternative to
eval()
with less security issues (according to MDN at least) is theFunction()
factory.This would output the result "1.5" in the console.
Also as a side note: Mixed fractions like 1 1/2 will not work with neither
eval()
nor the solution withFunction()
as written as they both stumble on the space.To convert a fraction to a decimal, just divide the top number by the bottom number. 5 divided by 3 would be 5/3 or 1.67. Much like:
Hope this helps, haha
I have a function I use to handle integers, mixed fractions (including unicode vulgar fraction characters), and decimals. Probably needs some polishing but it works for my purpose (recipe ingredient list parsing).
Inputs
"2 1/2"
,"2½"
,"2 ½"
, and"2.5"
will all return2.5
. Examples:One thing it doesn't handle is decimals within the fraction, e.g.
"2.5 / 5"
.