如何将varchar 1,760,862.8185919转换为在SQL Server 2012或decimal中浮动?
DECLARE @n varchar(100) = '1,760,862.8185919'
DECLARE @f float = ??
答案 0 :(得分:2)
你需要施放它,但首先删除逗号:
DECLARE @n varchar(100) = '1,760,862.8185919'
要使用CAST
转换,请执行以下操作:
DECLARE @f float = CAST(REPLACE(@n, ',', '') AS FLOAT)
或者,使用CONVERT
:
DECLARE @f float = CONVERT(float, REPLACE(@n, ',', ''))
首先转换为MONEY
然后转换为VARCHAR
,您可以转换回来(精度不足):
DECLARE @new_n VARCHAR(100) = CONVERT(VARCHAR, CAST(@f AS MONEY), 1)
答案 1 :(得分:1)
Declare @n varchar(100)
set @n = '1,760,862.8185919'
select convert(float,Replace(@n,',',''))
答案 2 :(得分:1)
逗号可能是您的问题,因此请在转换前删除它们:
DECLARE @f float = CONVERT(float, REPLACE(@n, ',', ''))
或者
DECLARE @f decimal(20, 8) = CONVERT(decimal(20, 8), REPLACE(@n, ',', ''))
利用SQL Server 2012功能,您可能希望改为使用TRY_CONVERT
:
DECLARE @f float = TRY_CONVERT(float, REPLACE(@n, ',', ''))
或者
DECLARE @f decimal(20, 8) = TRY_CONVERT(decimal(20, 8), REPLACE(@n, ',', ''))
如果转换失败(而不是引发错误),结果将是NULL
。
答案 3 :(得分:0)
你试过这个吗?
select @f = cast(replace(@n, ',', '') as float);
答案 4 :(得分:0)
这应该有效
DECLARE @n varchar(100) = '1,760,862.8185919'
DECLARE @f NUMERIC(25,10)
SET @f = CAST(REPLACE(@n,',','') AS NUMERIC(25,10))
PRINT @f