Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@drifterz28
Last active September 8, 2019 21:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save drifterz28/6971440 to your computer and use it in GitHub Desktop.
Save drifterz28/6971440 to your computer and use it in GitHub Desktop.
Fractions to Decimals function, needs to be able to have hole numbers and floats entered in as well as fractions
function toDeci(fraction) {
var result, wholeNum = 0, frac, deci = 0;
if(fraction.search('/') >= 0){
if(fraction.search('-') >= 0){
var wholeNum = fraction.split('-');
frac = wholeNum[1];
wholeNum = parseInt(wholeNum, 10);
}else{
frac = fraction;
}
if(fraction.search('/') >=0){
frac = frac.split('/');
deci = parseInt(frac[0], 10) / parseInt(frac[1], 10);
}
result = wholeNum + deci;
}else{
result = +fraction;
}
return result.toFixed(2);
}
console.log('1 ',toDeci("1-7/16"));
console.log('2 ',toDeci("5/8"));
console.log('3 ',toDeci("3-3/16"));
console.log('4 ',toDeci("12"));
console.log('5 ',toDeci("12.20"));
console.log('5 ',toDeci("1"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment