我正在使用SQL Server 2008,因此FORMAT功能不可用。是否有一种从十进制中删除前导零和尾随零的简洁方法。
我在堆栈溢出时发现的其他答案并未涵盖所有情况。
我希望能够做到这样的事情:
DECLARE @d decimal(9,6) = 12.345
SELECT removezeros(@d)
我意识到结果将是一个字符串。
它适用于以下所有情况:
0.123000 -> 0.123
1.23 -> 1.23
012.003450 -> 12.00345
1.00 -> 1
答案 0 :(得分:2)
create table #t(id decimal(9,6))
insert into #t values(0.123000),(012.3879000),(1.23),(1.00)
select cast(id as float) from #t
答案 1 :(得分:0)
这很糟糕,但似乎适用于花车和数字。如果您的值是浮点数,则键将首先转换为数字。
declare @val numeric(18,5) = 012.003450;
SELECT ISNULL(REPLACE(RTRIM(REPLACE(REPLACE(RTRIM(REPLACE(CAST(@val as nvarchar(max)),'0',' ')),' ','0'),'.',' ')),' ','.'),'');
答案 2 :(得分:-1)
有几种方法可以做到这一点,请尝试以下方法。
USE AdventureWorks2012;
GO
SELECT TOP(5)CurrencyRateID, EndOfDayRate
,FORMAT(EndOfDayRate, 'N', 'en-us') AS 'Number Format'
,FORMAT(EndOfDayRate, 'G', 'en-us') AS 'General Format'
,FORMAT(EndOfDayRate, 'C', 'en-us') AS 'Currency Format'
FROM Sales.CurrencyRate
ORDER BY CurrencyRateID;
这是结果集。
CurrencyRateID EndOfDayRate Numeric Format General Format Currency Format
-------------- ------------ -------------- -------------- ---------------
1 1.0002 1.00 1.0002 $1.00
2 1.55 1.55 1.5500 $1.55
3 1.9419 1.94 1.9419 $1.94
4 1.4683 1.47 1.4683 $1.47
5 8.2784 8.28 8.2784 $8.28
(5 row(s) affected)
可以在以下链接中找到 http://msdn.microsoft.com/en-us/library/hh213505.aspx