Turning Floats into Their Closest (UTF-8 Character) Fraction.
- by Mark Tomlin
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 ¼ ¼
case $decimal > 0.375 && $decimal < 0.625:
return $number . '½'; # 189 ½ ½
case $decimal > 0.625 && $decimal < 0.875:
return $number . '¾'; # 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!