如何转换十进制$ attribute ['text'];变成opencart的一小部分 [英] How to convert a decimal $attribute['text']; into a fraction in opencart

查看:84
本文介绍了如何转换十进制$ attribute ['text'];变成opencart的一小部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Opencart 2.3及更高版本中工作.我遇到了需要将小数转换为分数的情况.我正在使用category.tpl页面,我们将产品输出到该页面的列表中.属性因产品而异.

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.

示例;一页具有颜色",长度A"和长度B"属性. 产品A的数据当前在图表中输出为:蓝色,5.5、10.75. 我们希望它输出:蓝色,5 1/2、10 3/4

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

总有没有放置变量$ attribute ['text'];进入过滤器,会吐出一个分数(而不是小数)?另外,请注意,我们需要Blue才能吐出Blue.

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.

-谢谢Michael P.

-Thanks, Michael P.

这是下面的代码:

  <?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 } ?>

推荐答案

借助以下算法:将浮点小数转换为分数

尝试一下:

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

这篇关于如何转换十进制$ attribute ['text'];变成opencart的一小部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆