sqlsqliteroundingfloorceil

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.


Solution

  • 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