Detailed explanation of SQL Server rounding


Preface

Rounding is a common operation in SQL Server mathematical calculations, often used to precisely control the number of decimal places or integers. But when using it, we need to understand the different ways of rounding.

SQL Server has three rounding methods: ROUND, CEILING, and FLOOR. The results of each method are also different.

提示:以下是本篇文章正文内容,下面案例可供参考

1. ROUND

The ROUND method is the most commonly used rounding method. The ROUND method will use the one decimal place after the decimal point. If it is less than or equal to 4, it will discard the one decimal point; if the decimal point is greater than 5, it will carry. If it is equal to 5, the carry is determined based on whether there is a non-zero digit after the decimal point.

SELECT ROUND(10.5, 0); --结果为11
SELECT ROUND(10.4, 0); --结果为10

In the first example, 10.5 is rounded to 11, and in the second example, 10.4 is rounded to 10.

2. CEILING and FLOOR

1、CEILING

The CEILING method rounds the number up.

SELECT CEILING(1.5); --结果为2
SELECT CEILING(1.4); --结果为2

In the first example, 1.5 is rounded up to 2, and in the second example, 1.4 is rounded up to 2.

2、FLOOR

The FLOOR method rounds the number down.

SELECT FLOOR(1.5); --结果为1
SELECT FLOOR(1.4); --结果为1

In the first example, 1.5 is rounded down to 1, and in the second example, 1.4 is rounded down to 1.

4. Accuracy

When using the ROUND method for rounding, you need to pay attention to accuracy issues.

SELECT ROUND(1234.5678, 2); --结果为1234.5700

In this example, we want to preserve two decimal places, but the result is 1234.5700. This is because in the ROUND method, zero padding is performed after rounding. If we want to preserve the exact number of decimal places, we can use the CAST or CONVERT method.

SELECT CAST(1234.5678 AS numeric(10,2)); --结果为1234.57

Summarize

There are three ways of rounding in SQL Server: ROUND, CEILING and FLOOR. Their functions are to retain decimals, round up and round down respectively. When using the ROUND method for rounding, you need to pay attention to accuracy issues.

Guess you like

Origin blog.csdn.net/hsuehgw/article/details/132611877