A roundabout way of rounding



  • Saw this on http://www.consumer.gov/weightloss/bmi.htm when I was looking up the formula to calculate Body Mass Index. It's well known that Javascript's round() function doesn't allow the coder to specify how many decimal places to round out to. Still, this is solved easily by something like round(num*100)/100, for example. Apparently the coder of cal_bmi() didn't like how hackish that solution seemed, and instead did this...

    function cal_bmi(lbs, ins)
    {
      h2 = ins * ins;
      bmi = lbs/h2 * 703;
      f_bmi = Math.floor(bmi);
      diff  = bmi - f_bmi;
      diff = diff * 10;
      diff = Math.round(diff);
      if (diff == 10)
      { 
        // Add up to next
        f_bmi += 1;
        diff = 0;
      }
      bmi = f_bmi + "." + diff;
      return bmi;
    }



  • Just an FYI:  the formula is m/(h^2) where m is your body mass in kilos and h is your height in metres.  For example, I weigh 71 kg and stand 164cm (i.e. 1.64m), yielding about 26.4.  The 703 in the formula above is the conversion factor for pounds per square inch to kilos per square metre.  

    (And yeah, I know that has nothing to do with the WTF, but it answers the original question) 

     

     


Log in to reply