如何将十进制值转换为varchar值

时间:2016-10-07 08:51:09

标签: sql-server

我的值包含十进制(15,7)作为数据类型。它包含小数点后5位数。我的价值是:123.1071570。当我尝试将值转换为“varchar”时,然后在输出中得到123.107。将值转换为varchar后,我希望结果为123.107157。

我尝试过:

DECLARE @test1 decimal(15,7),
        @test2 nvarchar(10)

SELECT @test1 = 123.1071570

--Case 1 :
SELECT cast(@test1 as float) AS value1  
-- output : 123.107157  -- Value which I got after using cast()

-- I want to concate the value with string, so I need to convert it to varchar,
SELECT 'value is: '+convert(varchar,cast(@test1 as float)) AS value2     
-- output 
-- value is: 123.107  ---- Value which I got after converting it to varchar

-- Case 2 : 
SELECT convert(DOUBLE PRECISION, @test1)  AS value1  
-- output : 123.107157  -- Value which I got after using DOUBLE


SELECT 'value is: '+convert(varchar,convert(DOUBLE PRECISION, @test1)) AS value2     
-- output 
-- value is: 123.107  ---- Value which I got after converting it to varchar

我希望输出为:“值为:123.107157”

我想从我的值中删除尾随零。 我的值可以是任何东西,但在使用Double的Cast()之后,当我将它转换为varchar时,我想要从cast或Double获得相同的结果。

4 个答案:

答案 0 :(得分:1)

棘手的XML(从SQL Server 2008开始):)

DECLARE @x xml

DECLARE @t TABLE (
    digit decimal(15,7)
)

INSERT INTO @t VALUES
(123.1071570),
(123.1200000),
(123.0000000)

SELECT @x = (
    SELECT digit as d
    FROM @t
    FOR XML PATH('')
)

SELECT 'Value is: '+CAST(t.c.query('. cast as xs:decimal?') as nvarchar(max))
FROM @x.nodes('/d') as t(c)

输出:

Value is: 123.107157
Value is: 123.12
Value is: 123

答案 1 :(得分:0)

如此处所述:CAST and CONVERT (Transact-SQL)

DECLARE @myval decimal (15, 7);
SET @myval = 123.1071570;
SELECT CONVERT(decimal(15,7), CONVERT(VARCHAR(255), @myval));

正如您在评论中提到的,如果您没有固定长度,可以使用此选项:

DECLARE @myval decimal (15, 7);
SET @myval = 123.1200000 ;
SELECT CASt(CAST(CAST(@myval AS DECIMAL(15, 7)) AS FLOAT) AS NVARCHAR(255))

答案 2 :(得分:0)

你能尝试这种方法吗?

DECLARE @myval decimal (15, 7);
SET @myval = 123.1071570;
SELECT CAST(CAST(@myval AS DECIMAL(15, 7)) AS FLOAT)

结果:123.107157

答案 3 :(得分:0)

只需将值转换为nvarchar。

使用以下查询。

DECLARE @test1 decimal(15,7),
    @test2 nvarchar(10)

SET @test1 = 123.1071570

SELECT cast(@test1 as nvarchar(20)) AS value1