简体   繁体   English

是否可以在保持小数形式的同时在 SQL 中舍入小于 1 的数字

[英]Is It Possible to Round a Number Smaller Than 1 In SQL While Keeping In Decimal Form

I am not finding the solution to this issue despite looking specifically for it.尽管专门寻找它,但我没有找到解决此问题的方法。

The below query is me trying to get the last decimal places to appear properly.下面的查询是我试图让最后一个小数位正确显示。

select CAST(CAST(33 as float)/100 as decimal(5,3))

From here I am looking for how to round properly to .33 or if the result were .339 to round up to .34从这里我正在寻找如何正确四舍五入到 0.33 或者如果结果是 0.339 到四舍五入到 0.34

What I am finding is that it will only round down to 0 because it is not a whole number.我发现它只会向下舍入为 0,因为它不是整数。

Can someone point me in the right direction or if there is no good way let me know.有人可以指出我正确的方向,或者如果没有好的方法让我知道。

Make sure your denominator isn't treated as an integer.确保您的分母不被视为整数。 You could tack on a .0 or CAST or CONVERT it.您可以添加.0CASTCONVERT In the case where you'd expect rounding down to occur:在您希望四舍五入发生的情况下:

SELECT 331 / 1000.0;
-- gives 0.331000

SELECT ROUND(331 / 1000.0, 2);
-- gives 0.330000

SELECT CAST(ROUND(331 / 1000.0, 2) AS DECIMAL(5, 2));
-- gives 0.33

In the case where you'd be expect rounding up to occur:如果您希望四舍五入发生:

SELECT 339 / 1000.0;
-- gives 0.339000

SELECT ROUND(339 / 1000.0, 2);
-- gives 0.340000

SELECT CAST(ROUND(339 / 1000.0, 2) AS DECIMAL(5, 2));
-- gives 0.34

Note: you may not need to do both ROUND and CAST since I believe the rounding occurs implicitly, but it makes the intent more clear if you choose to write it as such.注意:您可能不需要同时执行ROUNDCAST因为我相信四舍五入是隐式发生的,但是如果您选择这样编写它会使意图更加清晰。

You can try this:你可以试试这个:

MySQL: MySQL:

select ROUND(339/1000,2)
0.34

select ROUND(33/100,2)
0.33

SQL Server: SQL 服务器:

select ROUND(339/1000.0,2)
0.340000

select ROUND(33/100.0,2)
0.330000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM