如何在SQL中将Float转换为Varchar

时间:2013-07-20 09:54:44

标签: sql sql-server tsql

我这样做

declare @num float = 7708369000

select  @num as [float], 
    convert(varchar, @num) as [varchar]

它给了我这个

float                  varchar
---------------------- ------------------------------
7708369000             7.70837e+009

但我想要这个

float                  varchar
---------------------- ------------------------------
7708369000             7708369000

请帮忙。

4 个答案:

答案 0 :(得分:15)

首先将其转换为十进制,

CAST(CAST(@num AS DECIMAL(20)) AS VARCHAR(20))

答案 1 :(得分:6)

尝试使用Str函数而不是使用convert

DECLARE @num float = 7708369000;    
SELECT Str(@num);

答案 2 :(得分:2)

尝试以下变体之一(值表示BigInt的最大值和其他Max类型值),以满足您的需求。 http://sqlfiddle.com/#!6/745c8f/1

CREATE TABLE Table1 
(
   FloatDefault float,  --Default is 24 bits giving 7 digit precision and 4 bytes storage
   Float24 float(24),   --Max for 4 bytes storage, 24 bits giving 7 digit precision and 4 bytes storage
   Float53 float(53)    --Max for 8 bytes storage, 53 bits giving 15 digit precision and 8 bytes storage
);

INSERT INTO Table1 VALUES(-9223372036854775808, -9223372036854775808, -9223372036854775808); --Max Negative Value of a Big Int
INSERT INTO Table1 VALUES(9223372036854775807, 9223372036854775807, 9223372036854775807);  --Max Positive Value of a Big Int
INSERT INTO Table1 VALUES(-2147483648, -2147483648, -2147483648); --Max Negative Value of a Big Int
INSERT INTO Table1 VALUES(2147483647, 2147483647, 2147483647);  --Max Positive Value of a Big Int
INSERT INTO Table1 VALUES(123456789012345678901234567890, 123456789012345678901234567890, 123456789012345678901234567890);
INSERT INTO Table1 VALUES(123456789012345678901234567890.12345678, 123456789012345678901234567890.12345678, 123456789012345678901234567890.12345678);
INSERT INTO Table1 VALUES(1234567890, 1234567890, 1234567890);
INSERT INTO Table1 VALUES(1234567890.0123456789, 1234567890.0123456789, 1234567890.0123456789);
INSERT INTO Table1 VALUES(22.0/7.0, 22.0/7.0, 22.0/7.0); -- Value of Pi
INSERT INTO Table1 VALUES(1, 1, 1);
INSERT INTO Table1 VALUES(2.0, 2.0, 2.0);
INSERT INTO Table1 VALUES(2000.0, 2000.0, 2000.0);

SELECT 
   FloatDefault,
   Float24,
   Float53,   
   CAST(CAST(Float53  AS NUMERIC(38)) AS VARCHAR(100)), -- 38 is the max precision 
   CAST(CAST(Float53  AS NUMERIC(38,5)) AS VARCHAR(100)), 
   STR(Float53),
   STR(Float53, 38),
   STR(Float53, 38,5),
   LTRIM(RTRIM(STR(Float53, 38,5))),
   CONVERT(VARCHAR, Float53),
   CONVERT(VARCHAR(100), Float53),
   CONVERT(NUMERIC(38,5), Float53)
FROM Table1
GO

答案 3 :(得分:0)

使用以下功能:

STR(数字,长度,十进制)

  • number 是要转换为字符串的数字值
  • length 是结果字符串的长度。默认值为10
  • 十进制是要舍入的小数位数。默认值为0

参考:STR (Transact-SQL)