SQL 服务器回合()

SQL Server round()

我想对 1 的值进行舍入 select

例如:

select width from Home

width的结果是“3.999999999999999”

我想成为“3.99”或“3.9”

如果您想要 3.99 或 3.9 的值,那么您不需要 round()。你想要floor()。但是,这适用于整数,但不适用于小数。

cast(width as decimal(10,2)) 的幼稚方法将 return 4.00round(width, 2) 也是如此。一种方法是减去少量。所以:

select cast(width - 0.005 as decimal(10, 2))

应该给你 "3.99"。

如果您只需要两个小数值,您可以乘以 100,对结果进行取整并除以 100(这是必需的,因为 floor 只能将数字取整为整数):

select floor(width * 100) / 100 from Home  

步骤如下

3.99999999 * 100 = 399.999999    --- Multiply by 100
floor(399.999999) = 399          --- floor 
399 / 100 = 3.99                 --- Divide by 100

也可以使用不同形式的 round function with a third parameter

当第三个参数不为 0 时,结果将被截断而不是四舍五入

Syntax

ROUND ( numeric_expression , length [ ,function ] )

Arguments

numeric_expression Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.

length Is the precision to which numeric_expression is to be rounded. length must be an expression of type tinyint, smallint, or int. When length is a positive number, numeric_expression is rounded to the number of decimal positions specified by length. When length is a negative number, numeric_expression is rounded on the left side of the decimal point, as specified by length.

function Is the type of operation to perform. function must be tinyint, smallint, or int. When function is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.

这里是 select 使用这个版本的 round:

 select round(width, 2, 1) from Home 

ROUND(width, 1 or 2, 1) 应该最适合您。示例:

SELECT CONVERT(NUMERIC(13,2), ROUND(width, 2, 1))
FROM Home

将 return 3.99,并且

SELECT CONVERT(NUMERIC(13,1), ROUND(width, 1, 1))
FROM Home

将return3.9

这很简单,如果你想要结果 3.9 那么

select round(width,1) from Home

如果您需要结果 3.99 然后使用..

select round(width,2) from Home