CEIL and FLOOR in SQLite

人盡茶涼 提交于 2019-12-10 21:09:16

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/54399936/ceil-and-floor-in-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!