How to round number?

3

I need to use the following rounding logic:

Numbers between x.1 and x.9 will be rounded to x.5, ie, you would use examples like this:

1.0 = 1;
1.2 = 1.5;
1.9 = 1.5;

Any ideas on how to do this? I tried to find a PHP function ready but I could not find it.

    
asked by anonymous 02.06.2017 / 17:11

2 answers

1

You can use the fmod() function.

function arred ($n) {
    $r = fmod($n, 1.0);
    if ($r != 0) {
        return $n - $r + 0.5;
    } else {
        return $n;
    }
}

Test script: link .

    
02.06.2017 / 19:03
0

You can simply check that the integer value is equal, that is:

$inteiro = intval($numero);

if(($numero - $inteiro) !== 0e0){
      // Então adicionar $inteiro + 0.5
}

Could do something like:

function arredondar(float $numero) : string {

        $inteiro = intval($numero); 
        $adicionar = '0';

        if(($numero - $inteiro) !== 0e0){
            $adicionar = '0.5' * ($numero > 0 ?: -1);
        }

        return bcadd($inteiro, $adicionar, 1);
}

Try this.

I do not think there's much to explain. If the result of $numero - $inteiro is different from 0 it will add 0.5 (or -0.5 if the number is negative).

One other option, it would be easier to just concatenate .5 to integer if it falls into the condition, this would remove the need for any sum.

function arredondar(float $numero) : float {

        $inteiro = intval($numero); 

        if(($numero - $inteiro) !== 0e0){
            $inteiro .= '.5';
        }

        return $inteiro;
}

Test this.

If you want to round normally use round() .

    
03.06.2017 / 04:36