How do I convert "1 1/4" to 1.25?
I want to take user input and convert it to the logical numerical equivalent. I say logical because 2 R and R 2 need to be 2(has to do with measuring chiropractic adjustments). Everything worked until they needed to be able to use mixed fractions.
Is there a library for this?
The only number that does not work is "1 1/4" which is converted in error to "2.75".
// Sample input
var values = ["2.5", "1 1/4", "1/4", "2 R", "R 2"];
function l(msg) {
console.log(msg)
}
function toDecimal(x) {
if (x.indexOf('/') != -1) {
var parts = x.split(" ")
var decParts = parts[1].split("/")
return parseInt(parts[0], 10) + (parseInt(decParts[0], 10) / parseInt(decParts[1], 10))
} else {
return x
}
}
function total_it_up(values){
var total = 0,
value = 0
if(values === undefined)
return 0
$.each(values, function(index, value){
value = value.replace(/[^0-9./]+/g, "")
value = eval(value)
l(value)
total += parseFloat(value)
})
return total
}
SOLUTION
function toDecimal(x) {
if (x.indexOf('/') != -1) {
var parts = x.split(" ")
var decParts;
if (parts.length > 1) {
decParts = parts[1].split("/");
}
else {
decParts = parts[0].split("/");
parts[0] = 0;
}
return parseInt(parts[0], 10) + (parseInt(decParts[0], 10) / parseInt(decParts[1], 10))
} else {
return x
}
}
function total_it_up(values){
var total = 0;
if(values === undefined)
return 0;
$.each(values, function(index, value){
total += parseFloat(toDecimal($.trim(value.replace(/[^0-9./ ]+/g, ""))));
})
return total;
}