Search code examples
phpunit-conversion

Prettifying a conversion from m(metres) to feet(') and inches ('')


I'm creating table for defining an individual's BMI. The chart (as yet) doesn't take input (because I want to make the thing work stand-alone, first), but it does show (on parallel axes) the height in both metres and feet/inches.

In order to do this I'm defining the metres' start point and range and then converting the defined metres variables into feet/inches, to do which I've come up with (please don't laugh...) the following:

<?php
        $m; // height in m

        $hInInches = ($m*3.2808399)*12;

        $hInImp = explode(".",$hInInches);

        $hInFt = $hInImp[0];

        $hInInches = substr(12*$hInImp[1],0,2);
?>

I was wondering if anyone has any prettier, more economical, more accurate means by which this could be done, since this is being run inside of a for () loop to generate x numbers of rows (defined elswhere), and I'd like (if possible) to reduce the load...


Solution

  • Here is an approach, in psuedo-code:

    inches_per_meter = 39.3700787
    inches_total = round(meters * inches_per_meter)  /* round to integer */
    feet = inches_total / 12  /* assumes division truncates result; if not use floor() */
    inches = inches_total % 12 /* modulus */
    

    You could pull out the 12 to a constant as well...