如何在 MySQL 中四舍五入到最接近的整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12361220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 14:47:43  来源:igfitidea点击:

How to round down to nearest integer in MySQL?

mysqlsqlrounding

提问by d-_-b

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

我如何四舍五入到 MySQL 中最接近的整数?

Example: 12345.7344 rounds to 12345

例子: 12345.7344 rounds to 12345

mysql's round()function rounds up.

mysql 的round()函数四舍五入。

I don't know how long the values nor the decimal places will be, could be 10 digits with 4 decimal places, could be 2 digits with 7 decimal places.

我不知道这些值和小数位有多长,可能是 10 位小数点后 4 位,也可能是 2 位小数位后 7 位。

回答by Jocelyn

Use FLOOR:

使用地板

SELECT FLOOR(your_field) FROM your_table

回答by Luca Fagioli

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

如果要将小数四舍五入为较低的整数,请使用FLOOR()。例子:

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

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

如果要将小数四舍五入为最接近的整数,请使用ROUND()。例子:

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

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

使用CEIL() ,如果你想你的小数四舍五入到整数。例子:

CEIL(1.9) => 2
CEIL(1.1) => 2

回答by hjpotter92

SELECT FLOOR(12345.7344);

Read more here.

在这里阅读更多。

回答by Guest

SUBSTRwill be better than FLOORin some cases because FLOOR has a "bug" as follow:

SUBSTR会比FLOOR在某些情况下更好,因为 FLOOR 有一个“错误”,如下所示:

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

回答by Ananya Verma

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
  • 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.

第二种解释:假设 12345.7344 整数。因此,12345.7344 - 0.5 = 12345.2344,四舍五入的结果将是 12345。

回答by VolkanCetinkaya

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

输出:19.147100 清除:985 添加:00

OR use this:

或者使用这个:

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

Output: 19.1471 Clear: 985

输出:19.1471 清除:985

回答by John Woo

Try this,

尝试这个,

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

or

或者

SELECT FLOOR(12345.7344)

SQLFiddle Demo

SQLFiddle 演示