T-SQL 四舍五入到小数位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3190688/
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-09-01 06:47:47  来源:igfitidea点击:

T-SQL Round to decimal places

sqlsql-servertsql

提问by madlan

How do I round the result of matchpercent to two decimal places (%)? I'm using the following to return some results:

如何将 matchpercent 的结果四舍五入到两位小数 (%)?我正在使用以下内容返回一些结果:

DECLARE @topRank int
set @topRank=(SELECT MAX(RANK) FROM
FREETEXTTABLE(titles, notes, 'recipe cuisine', 1))
SELECT 
    ftt.RANK, 
    (CAST(ftt.RANK as DECIMAL)/@topRank) as matchpercent, --Round this
    titles.title_id, 
    titles.title
FROM Titles
INNER JOIN 
FREETEXTTABLE(titles, notes, 'recipe cuisine') as ftt
ON
ftt.[KEY]=titles.title_id
ORDER BY ftt.RANK DESC

回答by OMG Ponies

CAST/CONVERT the result:

CAST/CONVERT 结果:

CAST((CAST(ftt.RANK as DECIMAL)/@topRank) AS DECIMAL(n,2)) as matchpercent,

...where nis a number large enough not to truncate left of the decimal point. That is to say, if you use "123.456", you need to use DECIMAL(7,2) because the total length is 7 digits.

...哪里n是一个大到足以不截断小数点左侧的数字。也就是说,如果使用“123.456”,则需要使用 DECIMAL(7,2),因为总长度为 7 位。