How To Convert A Decimal $attribute['text']; Into A Fraction In Opencart
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 ou
Solution 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:
functiondec2frac($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:
<divclass="attGroup matchHeight"><?phpecho dec2frac($attribute['text']); ?></div>
Solution 2:
with help of this algorithm: Converting float decimal to fraction
try this:
functionfloat2rat($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";
}
functionprintNiceAttr($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
Post a Comment for "How To Convert A Decimal $attribute['text']; Into A Fraction In Opencart"