Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function to move decimal to beginning

Tags:

php

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!

like image 604
puks1978 Avatar asked Sep 20 '26 07:09

puks1978


1 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 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;
}
like image 196
thordarson Avatar answered Sep 21 '26 21:09

thordarson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!