RobsonLittle 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:

49.052 miles

Total: 49 miles, 274 feet, 6 inches

Total miles: 49
Total feet: 258,994
Total inches: 3,107,934

Log

© 2004-20 robson | cc unless stated