Patch for round fractions in phpcookbook

From Finninday
Revision as of 23:12, 19 August 2012 by Rday (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The shopping list page shows decimal amounts instead of fractions. It would be nicer if it rounded decimals to the nearest simple fraction. This code does that to the nearest 1/8th.

Apply the change to modules/lists/print.php

<?php
foreach ($useLayout as $section) {
    // Print the header here if requested
    $html = makeHtmlList($items, $section);
    if (count($html)) {
        // print the header
        printHeader($section);
    }
    //foreach ($html as $line) echo str_replace("<td>","<td>hi ",$line);
    foreach ($html as $line) {
        $fraction = 0;
        if ( preg_match("/\.\d+/",$line,$matches)) {
            $decimal = $matches[0];
            if ( abs($decimal-0.5) < 0.0625) {
              $fraction = " 1/2";
              $diff = abs($decimal-0.5);
            }
            if ( abs($decimal-0.25) < 0.0625) {
              $diff = abs($decimal-0.25);
              $fraction = " 1/4";
            }
            if ( abs($decimal-0.75) < 0.0625) {
              $fraction = " 3/4";
              $diff = abs($decimal-0.75);
            }
            if ( abs($decimal-0.125) < 0.0625) {
              $fraction = " 1/8";
              $diff = abs($decimal-0.125);
            }
            if ( abs($decimal-0.375) < 0.0625) {
              $fraction = " 3/8";
              $diff = abs($decimal-0.375);
            }
            if ( abs($decimal-0.625) < 0.0625) {
              $fraction = " 5/8";
              $diff = abs($decimal-0.625);
            }
            if ( abs($decimal-0.875) < 0.0625) {
              $fraction = " 7/8";
              $diff = abs($decimal-0.875);
            }
            if ( $decimal < 0.0625) {
              $fraction = " a tiny fraction of ";
            }
        }
        if ($fraction) $line = str_replace($decimal, $fraction, $line);
        $line = str_replace("0 ", "", $line);
        echo $line;
    }
}
// Show the lost ingredients (no section matched)