JavaScript doesn’t have a lot of high-level mathematical functions built-in and for a project I am/was working on, I needed to change the quantities of all the ingredients in a listed recipe when a user changed the value of the “Serves” drop down box. For example:



change values of HTML with SELECT box



Changing the drop down to 5 would require a 25% increase from the ORIGINAL values, resulting in:



multiply fraction convert to decimal first



You should note that this is not a 100% accurate conversion. For the sake of readability, I use Math.round several times. So in cases where a fraction might be 64/100 it is first rounded to 60/100, reduced to 6/10 then simplified to 3/5. So four one hundredths (.04) accuracy is lost in that conversion. If you need higher precision you can remove the round functions to produce similar results at the cost of losing readability.


//function to get highest common factor of two numbers (a fraction)
function HCF(u, v) { 
	var U = u, V = v
	while (true) {
		if (!(U%=V)) return V
		if (!(V%=U)) return U 
	} 
}
//convert a decimal into a fraction
function fraction(decimal){
 
	if(!decimal){
		decimal=this;
	}
	whole = String(decimal).split('.')[0];
	decimal = parseFloat("."+String(decimal).split('.')[1]);
	num = "1";
	for(z=0; z<String(decimal).length-2; z++){
		num += "0";
	}
	decimal = decimal*num;
	num = parseInt(num);
	for(z=2; z<decimal+1; z++){
		if(decimal%z==0 && num%z==0){
			decimal = decimal/z;
			num = num/z;
			z=2;
		}
	}
	//if format of fraction is xx/xxx
	if (decimal.toString().length == 2 && 
			num.toString().length == 3) {
                //reduce by removing trailing 0's
		decimal = Math.round(Math.round(decimal)/10);
		num = Math.round(Math.round(num)/10);
	}
	//if format of fraction is xx/xx
	else if (decimal.toString().length == 2 && 
			num.toString().length == 2) {
		decimal = Math.round(decimal/10);
		num = Math.round(num/10);
	}
	//get highest common factor to simplify
	var t = HCF(decimal, num);
 
	//return the fraction after simplifying it
	return ((whole==0)?"" : whole+" ")+decimal/t+"/"+num/t;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...