puks1978
puks1978

Reputation: 3697

PHP function to move decimal to beginning

I need a function in PHP to move the decimal to the beginning of the number if one exists otherwise if there is no decimal add 0. to 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 extend it to also move the decimal to the beginning like:

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 larger than 1.

Thanks!

Upvotes: 3

Views: 1776

Answers (2)

Raekye
Raekye

Reputation: 5131

There's a better way. Use some math properties - something like this (this will also bring numbers less than 0.1 up front; you didn't specify what we should do with say 0.001234 - if you want to leave numbers less than 0.1 alone, just add a 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);

Upvotes: 2

thordarson
thordarson

Reputation: 6251

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 loop version (recursion was the first thing that came to mind):

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

    return $number;
}

Upvotes: 2

Related Questions