SQL Server 中的整数除法四舍五入到小数点后两位
我需要除以 2 个整数,结果应四舍五入到小数点后两位。 实际数字如下所示:
Select 3/5
要实现四舍五入到小数点后两位,请将分子乘以浮点数:
select round(3.0 / 5 , 2)
尝试将两个数字转换为小数,如下所示:
select round ( CAST (3 as decimal(3,2)) / CAST (5 as decimal(3,2)) , 2)
但结果包含多于 2 位小数。
预期的结果是:
0.60
我怎样才能实现这一目标?
I need to divide 2 integers and the result should be rounded off to 2 decimal places.
Actual numbers look like this:
Select 3/5
To achieve rounding off to 2 decimal places multiplied the numerator with a float:
select round(3.0 / 5 , 2)
Tried casting both the numbers as decimal numbers like this:
select round ( CAST (3 as decimal(3,2)) / CAST (5 as decimal(3,2)) , 2)
But the result contains more than 2 decimal places.
The expected result is:
0.60
How can I achieve that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当我们除法时,我们可以使用整数,这将产生整数结果,或者通过添加小数点(带或不带零)来使用小数,这将产生小数结果,其小数位数由格式决定,或者通过添加 e 来实现浮点数,这将使用有效小数位数,而无需尾随零。以下测试架构演示了它们之间的差异。
我认为 ROUND(2e/3,2) 是达到小数点后两位的最简洁方法。
db<>fiddle 此处
When we divide we can use an integer, which will produce an integer result, or a decimal by adding a decimal point (with or without a zero) which will give a decimal result with the number of decimal places determined by the format, or a floating point by adding an e, which will use the number of significant decimal places without trailing zeros. The following test schema demonstrates the difference between them.
I would seem that
ROUND(2e/3,2)
is the most concise way to arrive at 2 decimal places.db<>fiddle here