PHP function to go from decimal to start

I need a function in PHP to move a decimal to the beginning of a number if it exists otherwise, unless there is no decimal 0 at the beginning.

I have:

function toDecimal($input){
    return (stripos($input, ".")!==false)? $input: "0." . $input;
}

      

which was provided in a previous question of mine (thanks @ shiplu.mokadd.im), but I need to expand it to also translate the decimal to the beginning, for example:

Input        Output
0.1234       0.1234
1.2345       0.12345
1234         0.1234
0.001234     0.001234

      

so basically the outputted number can never be greater than 1.

Thank!

+3


source to share


2 answers


A little recursive magic should do the trick:

function divideNumber($number, $divide_by, $max)
{
    if($number > $max)
    {
        return divideNumber($number/$divide_by, $divide_by, $max);
    }
    else
    {
        return $number;
    }
}

// Outputs 0.950
print(divideNumber(950, 10, 1));

      

EDIT:



Here's a version of the loop (recursion was the first thing that came to mind):

function divideNumber($number, $divide_by, $max)
{
    while($number > $max)
    {
        $number = $number / $divide_by;
    }

    return $number;
}

      

+2


source


There's a better way. Use some math properties - something like this (this will also cause the numbers to be less than 0.1 in front, you didn't specify what we should do, say 0.001234 - if you want to keep the numbers less than 0.1, just add branch)



function foo($num) {
    if ($num == 0) return $num; // can't take log of 0
    return $num / pow(10, ceil(log($num, 10)));
}

echo foo(10.23);

      

+2


source







All Articles