Robson » Little Red Book » Distance conversion #2

Chapter 1 - Question 8

Given a distance as a rational number of miles, convert it to an integer number of miles, feet and inches.

Solution 1

<?
   // generate a random number of miles
   $miles = mt_rand(2, 100) + (mt_rand(1, 1000) / 1000);
   // show the amount of miles
   echo $miles . ' miles';
   
   // work it out as one result
   $r_decimal = $miles - intval($miles);
   // take off the feet
   $r_feet = intval($r_decimal * 5280);
   // take the feet away from the inches
   $r_inches = ($r_decimal * 63360) % $r_feet;
   
   // show the information processed above
   echo '<br/> <br/>Total: '
      . intval($miles) . ' miles, '
      . $r_feet . ' feet, '
      . $r_inches . ' inches';    
   
   // show the individual parts
   echo '<br/> <br/>Total miles: ' . intval($miles)
      . '<br/>Total feet: ' . number_format(intval($miles * 5280))
      . '<br/>Total inches: ' . number_format(intval($miles * 63360));
?>

Which produces:

87.963 miles

Total: 87 miles, 5084 feet, 7 inches

Total miles: 87
Total feet: 464,444
Total inches: 5,573,335

Log

© 2004-17 robson | cc unless stated