简体   繁体   English

SQL中的舍入函数删除.00

[英]Round function in SQL remove .00

I want to round any float value with 2 decimal places while after decimal has values and if after decimal has no values like (.00) at that time will not be shown .00 我想用2个小数位舍入任何浮点值,而小数点后有值,如果小数点后没有类似(.00)的值,那么此时将不会显示.00

Please refer this code 请参考此代码

  Declare @num float
  Set @num = 123.23252
  --1. Result 123.23
  select CAST(ROUND(@num,2) as numeric(18,2))
  Set @num = 253.000012
  --2. Result 253.00
  select CAST(ROUND(@num,2) as numeric(18,2))

I need 1st result is ok but in 2nd result i want only 253 (not included .00). 我需要第一个结果是好的,但是在第二个结果中,我只需要253(不包括.00)。 These both functionality i want to be same function or method because we don't know exactly when @num has 123.23 or 253.000012. 这两个功能我想成为相同的功能或方法,因为我们不知道@num何时具有123.23或253.000012。

Please let me know the simple and optimized solution. 请让我知道简单且优化的解决方案。

Try this: 尝试这个:

Declare @num float
  Set @num = 123.23252
  --1. Result 123.23
  select CAST(ROUND(@num,2) as numeric(18,2))
  Set @num = 253.000012
  --2. Result 253.00

Use case when like this: 这样的用例:

    select 
    CASE 
        WHEN RIGHT(CAST(ROUND(@num,2) as numeric(18,2)),2)='00' THEN ROUND(@num,2) 
        ELSE CAST(ROUND(@num,2) as numeric(18,2)) 
    END

Or use IFF for SQL Server 2012: 或对SQL Server 2012使用IFF:

 select IFF(RIGHT(CAST(ROUND(@num,2) as numeric(18,2)),2)='00'
      , ROUND(@num,2), CAST(ROUND(@num,2) as numeric(18,2)) 

You can use Format to do this(SQL SERVER 2012+) 您可以使用格式来执行此操作(SQL SERVER 2012+)

    Set @num = 253.000012
  select FORMAT(CAST(ROUND(@num,2) as numeric(18,2)) , 'g15')
    --3. Result 253.00

        Set @num = 253.3000012
  select FORMAT(CAST(ROUND(@num,2) as numeric(18,2)) , 'g15')
    --4. Result 253.3

The presentation of data should be done by the client, not by the database, but if you insist, just round the float and keep it as float: 数据的呈现应该由客户端而不是数据库来完成,但是如果您坚持,只需将浮点数四舍五入并保持为浮点数即可:

declare @num1 float = 123.23252;
declare @num2 float = 253.000012;

select ROUND(@num1,2), ROUND(@num2,2)

result 结果

123.23  253

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

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