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

6

I was doing some testing in MySQL and then came the need to have to round a number to the largest. It would be something like:

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

Although I could do this, I wanted to avoid making if / else .

Is there a function that does this in MySQL? For example a function that if the value entered was 1.5 rounds to the largest, for 2 in the case?

    
asked by anonymous 13.09.2017 / 16:16

3 answers

7

I believe you are looking for CEILING(X) function. This CEILING() function, which can be used briefly as CEIL() , returns the smallest integer value not less than X.

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

Here are 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.

    
13.09.2017 / 16:17
6

You can use the ROUND() function, value and / or number of decimal places as a parameter. Here are some examples:

Passing only the value as a parameter:

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

Passing the value and number of decimal places, remembering that using ROUND(x, 0) would be equivalent to ROUND(x) . See:

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

See running SQLFiddle .

For more details, see in the documentation .

    
13.09.2017 / 16:29
3

Use the function ceiling (x) ??

SELECT CEILING(1.23);
//retorno: 2
    
13.09.2017 / 16:19