Drop 0 value in decimal places

断了今生、忘了曾经 提交于 2019-12-02 04:03:36

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.

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.

You could rather just cast to FLOAT.

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!