Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CEIL and FLOOR in SQLite

What is the cleanest method to find the ciel and floor of a number in SQLite? Unfortunately SQLite only has ROUND() function.

like image 394
Bertram Gilfoyle Avatar asked Jan 28 '19 10:01

Bertram Gilfoyle


People also ask

What is the difference between Ceil () and floor () functions?

The ceil function returns the smallest integer value which is greater than or equal to the specified number, whereas the floor function returns the largest integer value which is less than or equal to the specified number.

What is Ceil and floor in SQL?

Definition and UsageThe CEILING() function returns the smallest integer value that is larger than or equal to a number. Tip: Also look at the FLOOR() and ROUND() functions.

What is SQL Ceil?

The CEIL() function returns the smallest integer value that is bigger than or equal to a number. Note: This function is equal to the CEILING() function.

How do you divide in SQLite?

The SQLite divide ( / ) operator is used to divide one expression or numbers by another.


2 Answers

Formulas

Ceil : cast ( x as int ) + ( x > cast ( x as int ))
Take integer part of x and add 1 if decimal value is greater than 0

Floor : cast ( x as int ) - ( x < cast ( x as int ))
Take integer part of x and subtract 1 if decimal value is less than 0


Examples

Ceil :
SELECT (cast ( amount as int ) + ( amount > cast ( amount as int ))) AS amount FROM SALES WHERE id = 128;
Floor :
SELECT (cast ( amount as int ) - ( amount < cast ( amount as int ))) AS amount FROM SALES WHERE id = 128;



I have checked all the corner cases including negative number with MySQL ceil() and floor() functions.

Test result

like image 160
Bertram Gilfoyle Avatar answered Sep 18 '22 00:09

Bertram Gilfoyle


You can use ROUND() to the effect of CEIL and FLOOR if you add or subtract 0.5 from the number on hand. I like this more, because it's can be more readable.

Expanding on Anees' example :

Ceil : SELECT ROUND(amount+0.5, 0) AS amount FROM SALES WHERE id = 128;
Floor : SELECT ROUND(amount-0.5, 0) AS amount FROM SALES WHERE id = 128;

Thanks Anees for the comment below, I didn't think of that corner case either. His solution is more robust.

like image 26
hyperTrashPanda Avatar answered Sep 18 '22 00:09

hyperTrashPanda