MS SQL的ROUND函数用来数值的四舍五入

MS SQL的ROUND函数用来数值的四舍五入

MS SQL要进行数值的四舍五入,有一好用的函数ROUND。

语法 ROUND ( numeric_expression , length [ ,function ] )
参数
numeric_expression 精确数值或近似数值数据类别(bit 数据类型除外)的表达式。
length           numeric_expression 的舍入精度。
                     length 必须是 tinyint、smallint 或 int 类型的表达式。
                     如果 length 为正数,则将 numeric_expression 舍入到 length 指定的小数位数。
                     如果 length 为负数,则将 numeric_expression 小数点左边部分舍入到 length 指定的长度。
function        要执行的操作的类型。function 必须为 tinyint、smallint 或 int。
                    如果省略 function 或其值为 0(默认值),则将舍入 numeric_expression。
                    如果指定了 0 以外的值,则将截断 numeric_expression。

返回类型
返回与 numeric_expression 相同的类型。

备注
      始终返回一个值。
      如果 length 为负数,并且大于小数点前的数字个数,则 ROUND 将返回 0。
      示例 结果
      ROUND(748.58, -4)    0  

     如果 length 为负数,则无论什么数据类型,ROUND 都将返回一个舍入的 numeric_expression。
     示例 结果
    ROUND(748.58, -1)   750.00  
    ROUND(748.58, -2)   700.00
    ROUND(748.58, -3)   1000.00

以下示例显示了两个表达式,阐释使用了 ROUND 后,最后一位数将始终为估计值
ROUND(123.9994, 3)    123.9990
ROUND(123.9995, 3)    124.0000


以下示例显示舍入和近似值
ROUND(123.4545, 2) 123.4500
ROUND(123.45, -2)    100.00

以下示例使用了两个 SELECT 语句,用于阐释舍入和截断之间的区别。第一个语句舍入结果。第二个语句截断结果。
ROUND(150.75, 0)     151.00
ROUND(150.75, 0, 1) 150.00

以下题为有一station表,求lat_n和long_w的总和,结果精确到二位小数点。
Query the following two values from the STATION table:
The sum of all values in LAT_N rounded to a scale of decimal places.
The sum of all values in LONG_W rounded to a scale of decimal places.

Input Format
The STATION table is described as follows:

Field Type
ID Number
City varchar2(32)
state varchar2(2)
Lat_N number
Long_W number

where LAT_N is the northern latitude and LONG_W is the western longitude.

Output Format
Your results must be in the form:
lat lon
where is the sum of all values in LAT_N and is the sum of all values in LONG_W.
Both results must be rounded to a scale of decimal places.

此题还需要decimal/numeric数据类型,以及convert/cast转换函数的知识

decimal[ (p[ , s] )] 和 numeric[ (p[ , s] )]
固定精度和小数位数。使用最大精度时,有效值从 - 10^38 +1 到 10^38 - 1。decimal 的 ISO 同义词为 dec 和 dec(p, s)。numeric 在功能上等价于 decimal。

p(精度,Precision)
最多可以存储的十进制数字的总位数,包括小数点左边和右边的位数。该精度必须是从 1 到最大精度 38 之间的值。默认精度为 18。

s (小数位数,Scale)
小数点右边可以存储的十进制数字的最大位数。小数位数必须是从 0 到 p 之间的值。仅在指定精度后才可以指定小数位数。默认的小数位数为 0;因此,0 <= s <= p。最大存储大小基于精度而变化。

posted @ 2021-04-07 15:29  webccaa  阅读(291)  评论(0编辑  收藏  举报