How to round up number?

Asked

Viewed 312 times

3

I need to use the following logic to round up:

Numbers between x.1 and x.9 will be rounded to x.5, that is, it would look like this using examples:

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

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

  • 1

    PHP has similar functions, round, Ceil and floor.Already what you want, you would have to adapt. On the page itself of round have an example of what you want, maybe help you.

  • 1

    See how I gave a solution in C#: https://answall.com/a/21941/101

2 answers

1

You can use the function fmod()

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

Script with testing: http://codepad.org/slXVpUti.

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
}

You 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);
}

Test this.

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

Another, easier option would only be to concatenate the .5 to the whole number if it falls into 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 rent normally use round().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.