Turning Floats into Their Closest (UTF-8 Character) Fraction.

Posted by Mark Tomlin on Stack Overflow See other posts from Stack Overflow or by Mark Tomlin
Published on 2010-03-15T18:53:19Z Indexed on 2010/03/15 18:59 UTC
Read the original article Hit count: 304

Filed under:
|
|
|
|

I want to take any real number, and return the closest number, with the closest fraction as available in the UTF-8 character set, appropriate.

0/4 = 0.00 =   # < .125
1/4 = 0.25 = ¼ # > .125 & < .375
2/4 = 0.50 = ½ # > .375 & < .625
3/4 = 0.75 = ¾ # > .625 & < .875
4/4 = 1.00 =   # > .875

I made this function to do that task:

function displayFraction($realNumber)
{
    if (!is_float($realNumber))
    {
        return $realNumber;
    }
    list($number, $decimal) = explode('.', $realNumber);
    $decimal = '.' . $decimal;
    switch($decimal)
    {
        case $decimal < 0.125:
            return $number;
        case $decimal > 0.125 && $decimal < 0.375:
            return $number . '¼'; # 188 ¼ &#188;
        case $decimal > 0.375 && $decimal < 0.625:
            return $number . '½'; # 189 ½ &#189;
        case $decimal > 0.625 && $decimal < 0.875:
            return $number . '¾'; # 190 ¾ &#190;
        case $decimal < 0.875:
            return ++$number;
    }
}

What are the better / diffrent way to do this?

echo displayFraction(3.1) . PHP_EOL;      # Outputs: 3
echo displayFraction(3.141593) . PHP_EOL; # Outputs: 3¼
echo displayFraction(3.267432) . PHP_EOL; # Outputs: 3¼
echo displayFraction(3.38) . PHP_EOL;     # Outputs: 3½

Expand my mind!

© Stack Overflow or respective owner

Related posts about php

Related posts about best-practices