I am trying to make a cooking recipe calculator, which basically grabs all numbers and divides them (so far). On top of dividing all numbers, it will also turn decimals into fractions. This is important. Now, when I run my loop to look for numbers to replace, I have a problem when numbers on lines are greater than 1. If I enter 1 egg and 2 cups of milk
and tell it to divide by 2, it will do this:
first iteration:
find: 1 and replace 1 with 1/2
result: 1/2 egg and 2 cups of milk
second iteration:
find: 2 and replace 2 with 1
result: 1/1 egg and 2 cups of milk
If you understood that correctly, I would now have 1/1 2
. Why? Because on the second iteration, it will find 2
and replace it with 1
. I basically need to say:
if(number != fraction)
replace number;
How am I able to do that from my code?
JSFiddle: http://jsfiddle.net/fgzt82yk/8/
My loop:
for(i = 0; i < content.length; i++) {
//Finds numbers on the line
var number = content[i].match(regex);
//number == null if the line is empty
if(number != null) {
//There can be more than 1 number on each line, create a new loop
for(j = 0; j < number.length; j++) {
//Turns fractions into decimals
var evalNumber = eval(number[j]);
//Divides the number
var divided = parseFloat(evalNumber / selection);
//We need some kind of precision, so we won't get 0.1666667 and so on
var precision = selection;
if(precision == 2) {
precision = 0;
}
//Turns our decimal into a fraction (or a whole-number)
var newNum = Math.fraction(divided.toString(), precision);
//Replaces the original number from the content[i] (whole line) with the new number/fraction
content[i] = content[i].replace(number[j], newNum);
}
}
}
Added comments to make it more clear what each line means. It's the last line that bugs me.. I'm sure.
I am basically looking for a better way to apply the math to all numbers (decimals, fractions, mixed numbers, et cetera). So far it kinda works, but I am sure someone has a better way of doing it! Thanks for looking!