I'm trying to calculate square footage on the fly from the dimensions in a text string (so I can pass the total to a hidden form field). The strings are pulled from the database when a product is added to a list within the form, and the dimensions always reflect height x width but output can vary if both inches and feet are included:
10'x20' // 10 feet x 20 feet = 200 square feet
10'6x20' // 10 feet 6 inches x 20 feet = 210 square feet
8'x15'10 // 8 feet x 15 feet 10 inches = 126.67 square feet
I'm thinking the best approach is to use jQuery or JavaScript to convert everything to inches, do the calculation, and then divide by 12 to get square footage, but I'm stumped on how to make it work with an inconsistent string pattern.
Any suggestions on how to accomplish this? In case it helps, I'm populating the list on button click and passing the string in a "data-width" attribute.
let's say conversion from square inches to square foot is easy and it's true.
You can use this formula to do so: square_foot = (square_inches / 144)
for the conversion you can use simple JavaScript as you just need to split the string to get foot and inches part
// possible numbers
const num1 = "5'10";
const num2 = "6'0";
const num3 = "0'10";
const num4 = "5";
const num5 = "10'";
const changeFootToInches = (numberString) => {
let [foot, inches] = numberString.split("'");
// if inches is undefined means numberString is num4
// and num4 contains only inches so swap these values
if (inches === undefined) {
inches = foot;
foot = 0;
}
return (+(foot || 0) * 12 + +(inches || 0));
// use toFixed(limit) to use restrict the floating points
};
const getAreaInSquareFoot = (num1, num2) => {
const inchesNum1 = changeFootToInches(num1);
const inchesNum2 = changeFootToInches(num2);
return ((inchesNum1 * inchesNum2) / 144);
}
console.log(getAreaInSquareFoot(num1, num2));
console.log(getAreaInSquareFoot(num1, num3));
console.log(getAreaInSquareFoot(num1, num4));
console.log(getAreaInSquareFoot(num1, num5));
console.log(getAreaInSquareFoot(num1, num5));
console.log(getAreaInSquareFoot(num2, num4));
console.log(getAreaInSquareFoot(num3, num4));
console.log(getAreaInSquareFoot(num3, num5));
I hope you find this useful :)