Last active
September 8, 2019 21:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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