How to round down to nearest integer in MySQL?

前端 未结 7 1186
自闭症患者
自闭症患者 2020-12-24 04:26

How would I round down to the nearest integer in MySQL?

Example: 12345.7344 rounds to 12345

mysql\'s round() function rounds up.

相关标签:
7条回答
  • 2020-12-24 04:50

    Use FLOOR(), if you want to round your decimal to the lower integer. Examples:

    FLOOR(1.9) => 1
    FLOOR(1.1) => 1
    

    Use ROUND(), if you want to round your decimal to the nearest integer. Examples:

    ROUND(1.9) => 2
    ROUND(1.1) => 1
    

    Use CEIL(), if you want to round your decimal to the upper integer. Examples:

    CEIL(1.9) => 2
    CEIL(1.1) => 2
    
    0 讨论(0)
  • 2020-12-24 04:53

    Use FLOOR:

    SELECT FLOOR(your_field) FROM your_table
    
    0 讨论(0)
  • 2020-12-24 04:53

    SUBSTR will be better than FLOOR in some cases because FLOOR has a "bug" as follow:

    SELECT 25 * 9.54 + 0.5 -> 239.00
    
    SELECT FLOOR(25 * 9.54 + 0.5) -> 238  (oops!)
    
    SELECT SUBSTR((25*9.54+0.5),1,LOCATE('.',(25*9.54+0.5)) - 1) -> 239
    
    0 讨论(0)
  • 2020-12-24 04:59

    if you need decimals can use this

    DECLARE @Num NUMERIC(18, 7) = 19.1471985
    SELECT FLOOR(@Num * 10000) / 10000
    

    Output: 19.147100 Clear: 985 Add: 00

    OR use this:

    SELECT SUBSTRING(CONVERT(VARCHAR, @Num), 1, CHARINDEX('.', @Num) + 4)
    

    Output: 19.1471 Clear: 985

    0 讨论(0)
  • 2020-12-24 05:07

    Try this,

    SELECT SUBSTR(12345.7344,1,LOCATE('.', 12345.7344) - 1)
    

    or

    SELECT FLOOR(12345.7344)
    

    SQLFiddle Demo

    0 讨论(0)
  • 2020-12-24 05:09

    It can be done in the following two ways:

    • select floor(desired_field_value) from table
    • select round(desired_field_value-0.5) from table

    The 2nd-way explanation: Assume 12345.7344 integer. So, 12345.7344 - 0.5 = 12345.2344 and rounding off the result will be 12345.

    0 讨论(0)
提交回复
热议问题