Drop 0 value in decimal places

喜你入骨 提交于 2019-12-20 04:28:07

问题


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, 340.670000000000000000000, 96.00000000000000000000, 4400.56000000000000000000, 109.89000000000000000000, 109.00000000000000000000, 37.00000000000000000000,

Currently I'm using the query "select cast([Percent] as decimal(9,2)) as [Percent] from table" and will result in

Result

770.00, 340.67, 96.00, 4400.56, 109.89, 109.00, 37.00,

I want the result this actually:->

770, 340.67, 96, 4400.56, 109.89, 109, 37,


回答1:


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.




回答2:


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.




回答3:


You could rather just cast to FLOAT.




回答4:


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


来源:https://stackoverflow.com/questions/1831466/drop-0-value-in-decimal-places

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