Skip to content

Instantly share code, notes, and snippets.

@acorncom
Forked from drifterz28/fracToDeci.js
Last active August 29, 2015 14:00
Show Gist options
  • Save acorncom/11231248 to your computer and use it in GitHub Desktop.
Save acorncom/11231248 to your computer and use it in GitHub Desktop.
Updated to allow full whole numbers and then a fraction
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 if(fraction.search(' ') > 0){
var wholeNum = fraction.split(' ');
fraction = wholeNum[1];
wholeNum = parseInt(wholeNum,10);
} else{
frac = fraction;
}
if(fraction.search('/') >=0){
frac = fraction.split('/');
deci = parseInt(frac[0], 10) / parseInt(frac[1], 10);
}
result = wholeNum+deci;
}else{
result = fraction
}
return result;
}
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 1/4"));
console.log('5 ',toDeci("12.2"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment