How to convert a decimal $attribute['text'

2019-09-07 08:59发布

问题:

I am working in Opencart 2.3 & I have run into a situation where we need decimals converted into fractions. I am working with the category.tpl page, and we have our products outputted into a list on the page. The Attributes vary per product.

Example; One page has the Attributes Color, Length A, and Length B. Product A's data is currently outputting in the chart as: Blue, 5.5, 10.75. We would like it to output: Blue, 5 1/2, 10 3/4

Is there anyway to put the variable $attribute['text']; into a filter, that spits out a fraction (instead of the decimal)? Also, note that we would need Blue to spit out Blue still.

-Thanks, Michael P.

Here is the code below:

  <?php if ($product['attribute_groups']) { ?>
      <?php foreach ($product['attribute_groups'] as $attribute_group) { ?>
           <?php foreach ($attribute_group['attribute'] as $attribute) { ?>

  <div class="attGroup matchHeight"><?php echo $attribute['text']; ?> </div> 

               <?php } ?>
           <?php } ?>
        <?php } ?>

回答1:

Assuming there is only a few fractions being realisticly used, you might prevously register them, then use this registry to convert any decimal value found.

It might be something like this:

function dec2frac($x) {
    $dec_parts = [
        25 => '1/4',
        50 => '1/2',
        75 => '3/4',
    ];

    $int_part = floor($x);
    echo $dec_part = ($x - $int_part) * 100;
    if (isset($dec_parts[$dec_part])) {
        $x = $int_part . ' ' . $dec_parts[$dec_part];
    }
    return $x;
}

Then your HTML part would be:

<div class="attGroup matchHeight"><?php echo dec2frac($attribute['text']); ?> </div>


回答2:

with help of this algorithm: Converting float decimal to fraction

try this:

function float2rat($n, $tolerance = 1.e-6) {
    $h1=1; $h2=0;
    $k1=0; $k2=1;
    $b = 1/$n;
    do {
        $b = 1/$b;
        $a = floor($b);
        $aux = $h1; $h1 = $a*$h1+$h2; $h2 = $aux;
        $aux = $k1; $k1 = $a*$k1+$k2; $k2 = $aux;
        $b = $b-$a;
    } while (abs($n-$h1/$k1) > $n*$tolerance);

    return "$h1/$k1";
}


function printNiceAttr($attrString) {
    $arr = explode(',', $attrString);
    $color = trim($arr[0]);
    $size1A = explode('.', $arr[1]);
    $size1F =  float2rat((float) ('0.' . $size1A[1]));

    $size2A = explode('.', $arr[2]);
    $size2F =  float2rat((float) ('0.' . $size2A[1]));  
    return $color . ', ' . $size1A[0] . ' ' . $size1F . ', ' . $size2A[0] . ' ' . $size2F;
}

echo printNiceAttr('Blue, 5.5, 10.75'); //outputs Blue, 5 1/2, 10 3/4