简体   繁体   中英

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

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). 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.

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:

 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+)

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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