Drop 0 value in decimal places

后端 未结 4 1913
遥遥无期
遥遥无期 2021-01-26 18:55

I want to ask if anybody know the query to drop the 0 value in decimal..

E.g : A field name percent have these values

Percent

770.00000000000000000000,

相关标签:
4条回答
  • 2021-01-26 19:31

    You could use a combination of DECIMAL and FLOAT. Decimal first to round it down to 2 deciaml places, then float to remove unwanted 0's

    e.g.

    select cast(cast([Percent] as decimal(9,2)) AS FLOAT) as [Percent] 
    

    With the example of 340.69999999999999, first it round to 340.70, then it takes away the zero giving you 340.7. As with any rounding some precision will be lost.

    0 讨论(0)
  • 2021-01-26 19:35

    You could rather just cast to FLOAT.

    0 讨论(0)
  • 2021-01-26 19:40

    You can use CONVERT function twice, once to drop 0 by converting to float and once to convert it to varchar with style 128

    DECLARE @Sample AS TABLE
        (
         SomeNumber DECIMAL(26, 12)
        )
    
    INSERT INTO @Sample
        VALUES  ( 770.00000000000000000000 )
    ,           ( 340.670000000000000000000 )
    ,           ( 96.00000000000000000000 )
    ,           ( 4400.56000000000000000000 )
    ,           ( 109.89000000000000000000 )
    ,           ( 109.00000000000000000000 )
    ,           ( 37.00000000000000000000 )
    
    
    SELECT CONVERT(VARCHAR(25), CONVERT(FLOAT, SomeNumber), 128) AS NoZeros
        FROM @Sample
    
    0 讨论(0)
  • 2021-01-26 19:49

    This rather nasty TSQL might just do the job :

    select 
      case 
        right(
           cast(cast([percent] as decimal(9,2)) as nvarchar(11))
        ,2)
    
        when '00' then cast(cast([percent] as int) as nvarchar(11)) as [percent]
        else cast(cast([percent] as decimal(9,2)) as nvarchar(11)) as [percent]
    
     end
    from table
    

    of course it is always returning a string, but that's inherent to your demands, you are looking for a representation for a value...

    I think you should postpone that representation to where it makes more sense (report, datagrid?) and you have more tools (like string.format kinda tools) to do the job better.

    0 讨论(0)
提交回复
热议问题