How to round a number to the highest value in Mysql?

Asked

Viewed 8,795 times

6

I was doing some tests on Mysql and then the need arose to have to round a number to the largest. It would be something like:

if($numero == 1.5){
    $numero = 2;
}

Even though I could do it like this, I wanted to avoid doing it if/ else.

Isn’t there a function that does this in Mysql? For example, a function that if the entered value is 1.5 is rounded to the highest, to 2 in the case?

3 answers

7


I believe you seek the function CEILING(X). That function CEILING(), which can be used abbreviated as CEIL(), returns the smallest integer value not less than X.

In other words, "round the larger/round up" a value.

See some return examples:

mysql> SELECT CEILING(1.5);
            -> 2
mysql> SELECT CEILING(-2.3);
            -> -2
mysql> SELECT CEIL(7.83);
            -> 8
mysql> SELECT CEIL(10.5244655448);
            -> 11

You can see this SQL Fiddle that demonstrates one of the ways to accomplish what you want.

6

You can use the function ROUND(), passing the value and/or number of decimals as a parameter. See some examples:

Passing only the value as parameter:

mysql>SELECT ROUND(2.5); 
->resultado: 3

Passing the value and number of decimals, remembering that if using the ROUND(x, 0) would be equivalent to ROUND(x). Behold:

mysql>SELECT ROUND(2.5, 0); 
->resultado: 3
mysql>SELECT ROUND(1.5, 0); 
->resultado: 2
mysql>SELECT ROUND(1.6667, 0); 
->resultado: 2
mysql>SELECT ROUND(1.6667, 1); 
->resultado: 1.7
mysql>SELECT ROUND(1.6667, 2); 
->resultado: 1.67

Behold running on Sqlfiddle.

For more details, see in the documentation.

  • 2

    @Lucaslopes If you ROUND(1.5, 0); it will round to 2 friend. It would be 0 decimal places.

3

Use the function Ceiling(x)??

SELECT CEILING(1.23);
//retorno: 2

Browser other questions tagged

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