Find repeating part of repeating decimal -- PHP

php

Solution

Gotta say this isn't as easy as i thought it'd be. but i got it working. I'm sure there is a more efficient way of doing this, hopefully someone else will improve upon this. Especially the part where it gets printed.

$number1 =  $number / $divisor;
if(findRepeat( $number1 ) !== false)
{
    $result = findRepeat($number1);
    $leadingNum = strstr($number1, '.', true);
    $nonRepeat = substr($number1, strpos($number1, '.') + 1 , $result['position']);
    if($nonRepeat == '')
        $nonRepeat = '.';

    $repeat = substr($number1,strpos($number1,$nonRepeat) + strlen($nonRepeat), $result['patternSize']);
    $nonRepeat = $nonRepeat == '.' ? '.' : '.'.$nonRepeat;
    echo $leadingNum.$nonRepeat."<span style='text-decoration:overline'>".$repeat."</span>";

}
else
  echo number_format( $number1 , 6);

now for the function

function findRepeat($number)
{
    $maxLength = 6;
    $decimal = substr($number, strpos($number,'.') + 1 );
    if(strlen($decimal) >= $maxLength )
        $decimal = substr($decimal,0, $maxLength);
    else
        $maxLength = strlen($decimal);

    for($i =0; $i < $maxLength - 3; ++$i)
    {
        //check for single repeition
        if( $decimal[$i] == $decimal[$i + 1] &&  $decimal[$i + 1] == $decimal[$i+2])
            return array('position'=>$i,'patternSize'=>1);
        //triple repetition
        if(substr($decimal,$i,3) == substr($decimal, $i + 3, 3) )
            return array('position'=>$i,'patternSize'=>3);
        //double repetition
        if(substr($decimal,$i,2) == substr($decimal, $i + 2, 2) )
            return array('position'=>$i,'patternSize'=>2);
    }

    return false;
}

Problem

I'm randomly generating repeated decimals using this code... ``` do{ $divisor_array = array(3, 6, 9, 11, 22, 33); $divisor = $divisor_array[array_rand($divisor_array)]; $number = mt_rand(1, 100); $decimal_value = $number / $divisor; } while (strlen($decimal_value) < 5); echo $number / $divisor; ``` I want to then display that number with the repeating bar over the repeating part. Example: 5.83434343434343.... would be 5.8`<span style="text-decoration: overline;">34</span>` Any ideas on how to do this if the repeating decimals are being randomly generated?

Original source

Related problems