# Working With Fractions In PHP

Displaying Fractions In HTML

There are a few ways to display fractions in the web. The most common way is just to add a slash between 2 numbers, like so â€œ1/2â€. There are also special HTML characters that we can make fractions look more professional. Eg. to display 1/2, we can use the HTML code Â½. However, not many fractions are supported by HTML. So, you may be in trouble if you want to display 2/9 in HTML.

A better way to display a fraction is probably to use the superscript and subscript tags. The HTML will be 2/9. We can also use a â€œspecial slashâ€ â„ between 2 numbers instead of a normal slash ( / ) to make the fraction look better. The fraction will now look like this: 2â„9. Still not satisfied? With CSS, we can push the limit further.

If we define a css like this:

.fracNum, .fracDen {

font-size: 70%; } .fracNum { vertical-align: 0.5em; } .fracDen { vertical-align: -0.5em; }

and when implemented with the superscript and subscript tags :

2â„9

The fraction will now be displayed like this: 3â„16

* The fractions might not be displayed correctly because of the online editor.

Converting Decimals To Fraction – A Real Example

I wrote a program that let people frame their pictures online. When I was halfway through, I was told that the program should support imperial measurements (inches). The problem with working in inches is that very few people would say my picture is 6.34 inch width by 9.82 inch height; Most people would say 6 and 3/8 inch by 9 and 3/8 height for example.

The biggest problem now is that the framing engine calculates everything in mm. Instead of rewritting the whole engine, I figured out that what I need is just an interface to convert mm to inches. So, if I pass 300mm into a function, it should return me 11 and 3/4 as the answer. Dividing 300mm by 1 inch (25.4mm) will leave me with a long decimal. It would be silly to try and display a fraction for a decimal like 0.1111. The function should be intelligent enough to round off the decimal to something that can be easily displayed as a fraction. For example, if I round off 0.1111 to 0.125, I can display the fraction as 1/8 instead of 1111/100000. Time is running short and I need a simple and sweet solution.

Implementation

I would like to go through snipplets of code with explaination first before revealing everything. Feel free to jump to the end of the page and copy the whole function if you just want to implement it in your website. The code is written in PHP.

Part 1: Extracting the decimal in inches.

define(INCH_TO_MM, 25.4);

// 1 inch equals to 25.4mm

\$inch = \$mm / INCH_TO_MM;

\$pWhole = explode(‘.’,\$inch); \$pWhole = \$pWhole;

\$pDecimal = \$val-\$pWhole;

The measurement in mm is first converted to inches(with decimal). The decimal is then isolated from the whole number and stored in a var call \$pDecimal. Now, I need to store a list of all possible fractions with their mm equivalent in an array. I use intervals of 1/8 for the sake of simplicity.

Part 2: Rounding off to the closest inch interval.

\$fractionOption = array();

\$fractionOption[â€˜0/8â€™] = 0;

\$fractionOption[â€˜1/8â€™] = 0.125;

\$fractionOption[â€˜1/4â€™] = 0.25;

\$fractionOption[â€˜3/8â€™] = 0.375;

\$fractionOption[â€˜1/2â€™] = 0.5;

\$fractionOption[â€˜5/8â€™] = 0.625;

\$fractionOption[â€˜3/4â€™] = 0.75;

\$fractionOption[â€˜7/8â€™] = 0.875;

\$fractionOption[â€˜8/8â€™] = 1;

foreach (\$fractionOption as \$k => \$v) {

// Converted \$pDecimal back to mm to perform calculation

\$tmpV[\$k] = abs(\$pDecimal – \$v);

}

asort(\$tmpV,SORT_NUMERIC);

list(\$inch, \$mm) = each(\$tmpV);

This is the most important step in the whole conversion process. The foreach loop creates a new array called \$tmpV which stores the inch fraction as the key and the inch difference as the value. We will now sort \$tmpV with the minimum â€˜mmâ€™ value at the top and the maximum â€˜mmâ€™ value at the bottom using the â€˜asortâ€™ function. We are extracting the first entry in the array because it stores the minimum â€˜mmâ€™ difference. As you can see, what we are trying to do here is to round \$pDecimal off to the closest decimal value in the \$fractionOption array (ie, 0.125, 0.25, 0.375..etc).

I can now safely extract the first key-value pair in \$tmpV using the ‘list’ function. The \$inch var stores the inch representation that we want.

Part 3: Cleaning Up

\$inch = (\$inch == ‘0/8’) ? ”: \$inch; // round off to nearest whole number if 8/8 if (\$inch == ‘8/8’) { \$inch = ”;

\$pWhole++; }

We do not want to display the fraction if it is â€˜0/8â€™ or â€˜8/8â€™ because it is pretty much meaningless. However, if the fraction is â€˜8/8â€™, we have to increase the whole number by 1.

if (\$inch != ”) {

\$tFrac = explode(‘/’,\$inch);

\$fraction = “\$tFracâ„\$tFrac”; } else {

\$fraction = ”; } return “\$pWhole \$fraction”;

Remember that we eliminated any fractions that are ‘0/8’ or ‘8/8’? So we only need to process any fraction that falls within the range of ‘1/8’ to ‘7/8’. By splitting the fractions into numerators and denominators, we can now apply our CSS technique mentioned above.

The Whole Thing

As promised, the full code is displayed below:

function mmToInch (\$val) {

\$fractionOption = array();

\$fractionOption[‘0/8’] = 0;

\$fractionOption[‘1/8’] = 0.125;

\$fractionOption[‘1/4’] = 0.25;

\$fractionOption[‘3/8’] = 0.375;

\$fractionOption[‘1/2’] = 0.5;

\$fractionOption[‘5/8’] = 0.625;

\$fractionOption[‘3/4’] = 0.75;

\$fractionOption[‘7/8’] = 0.875;

\$fractionOption[‘8/8’] = 1;

define(INCH_TO_MM, 25.4);

\$val = \$val/INCH_TO_MM;

\$pWhole = explode(‘.’,\$val);

\$pWhole = \$pWhole;

\$pDecimal = \$val-\$pWhole;

foreach (\$fractionOption as \$k => \$v) {

\$tmpV[\$k] = abs(\$pDecimal – \$v);

}

asort(\$tmpV,SORT_NUMERIC);

list(\$inch, \$mm) = each(\$tmpV);

// nullify pWhole and pFraction

\$pWhole = (\$pWhole == 0) ? ”: \$pWhole;

\$inch = (\$inch == ‘0/8’) ? ”: \$inch;

// round off to nearest whole number if 8/8

if (\$inch == ‘8/8’) {

\$inch = ”;

\$pWhole++;

}

// strip inch and return fraction formatted in css

if (\$inch != ”) {

\$tFrac = explode(‘/’,\$inch);

\$fraction = “\$tFracâ„\$tFrac”;

}

else {

\$fraction = ”;

}

return \$pWhole.’ ‘.\$fraction; }

// testing echo “67.885 mm is equivalent to “.mmToInch(66.885).” inches”;

?>

The sourcecode can be dowloaded here ## Author: bpeh

Bernard Peh is a great passioner of web technologies and one of the co-founder of Sitecritic.net Website Design and Reviews. He works with experienced web designers and developers everyday, developing and designing commercial websites. He specialises mainly in SEO and PHP programming.