JavaScript Get inches from feet and inches measurement

It's often handy to allow your user to enter dimensions in the traditional format with a single and double quote. Example: 10'5"

This function will take an input in this form and return the number of inches.
function getInchesFromEnglish(input) {

	var feet, inches;
	
	input = trimIt(input);
	
	if (isNumber(input)) {
		// numbers only
		if (input < 50)
			return input * 12;
		else
			return input;
	}
	else if (input.indexOf("'") !== -1) {
		// has feet
		feet = trimIt( input.split("'")[0] );
		inches = 0;
		
		if (input.split("'").length > 1) {
			inches = trimIt(input.split("'")[1].replace('"',''));
			if (!inches)
				inches = 0;
		}
			
		return (feet * 12) + parseFloat(inches);
	}
	else {
		// has only inches
		inches = trimIt( input.split('"')[0] );		
		return inches;
	}
	
	
}


function isNumber(n) {
	return !isNaN(parseFloat(n)) && isFinite(n);
}

function trimIt(x) {
	return x.replace(/^\s+|\s+$/gm,'');
}
Posted by
Snippet Viewed 2282 times.

Share your JavaScript code snippets:

  • Get some recognition & a link back to your site.
  • Create your own code library.
  • Help your fellow developers, as they have helped you.

 

Submit | Browse

Most Recent javascript snippets

Most Viewed