I’m currently working on something that requires dealing with the inanities of multiple systems of measurement (thanks USA for doggedly sticking to use of the archaic imperial system).
Users can input their height, but to accommodate the US I need to offer the option to input heights in feet and inches.
I probably should be doing this client-side with a nice jQuery UI Slider but I’m going for a quick and dirty approach instead which will require server-side translation of the input.
Convert from Feet/Inches to Centimetres
/** * Converts a height value given in feet/inches to cm * * @param int $feet * @param int $inches * @return int */ public static function convert_to_cm($feet, $inches = 0) { $inches = ($feet * 12) + $inches; return (int) round($inches / 0.393701); }
Convert from Centimetres to Feet/Inches
/** * Converts a height value given in cm to feet and inches * * @param int $cm * @return array */ public static function convert_to_inches($cm) { $inches = round($cm * 0.393701); $result = [ 'ft' => intval($inches / 12), 'in' => $inches % 12, ]; return $result; }
I figured the most useful return value for converting to feet and inches was to send back an array so you can decide how to handle/format them in your controller/template.
Comments