phpmathdata-conversiontext-parsingunits-of-measurement

Parse feet and inches formatted string and convert to inches as a floating point value


In my database, there is a field called height that is a varchar(9) field. The end user selects a value from a pull-down list that contains values such as:

5' 0
5' 0 1/2
5' 1
5' 1 1/2
5' 2
5' 2 1/2
And so on up to...
7' 4

What I need to do is convert this string into numeric inches for the purpose of a server-side calculation. How can this be done?


Solution

  • you want to get separate variables for feet, inches and fraction first

    $toBeConverted = "5' 4 1/2";
    list($feet,$inches,$frac) = explode(' ',$toBeConverted . ' ');
    

    then add those values

    $total = ((str_replace("'",'',$feet) * 12) + $inches + ($frac == '1/2' ? (1/2) : 0));