2013-07-20 158 views
3

我這樣做如何浮動轉換爲varchar在SQL

declare @num float = 7708369000 

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

它給了我這個

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

但我想這

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

請幫助。

+0

簡單的谷歌搜索「格式化操作VARCHAR的浮動而不是在科學記數法」 ** **結果:http://bytes.com/topic/sql-server/answers/80603-formatting-float -varchar-but-scientific-notation – danihp

回答

14

將其轉換爲第一十進制,

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

小數部分怎麼樣? – EvAlex

+0

這似乎不正確,因爲它截斷了小數部分,因此只適用於小數部分爲0的數字 – CodeCowboyOrg

+1

將DECIMAL(20)更改爲DECIMAL(20,S),其中S是所需的小數位數。對於數據類型DECIMAL(P,S),S(比例)必須小於或等於P(精度)。 – Rieekan

5

嘗試使用Str函數,而不是使用轉換

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

工作,但預先掛好空白。 – yogi

+0

對不起,先寫錯了25和0個參數。上面編輯的解決方案應該可以正常工作,不應該引入任何空格。 –

+0

這看起來不正確,因爲它會截斷小數部分,因此只對小數部分有0的數字有效 – CodeCowboyOrg

2

嘗試下面的變體之一(值代表BigInt和其他最大值的最大值e值),以滿足您的需求。 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(123456789, 123456789, 123456789); 
INSERT INTO Table1 VALUES(123456789.12345678, 123456789.12345678, 123456789.12345678); 
INSERT INTO Table1 VALUES(1234567890, 1234567890, 1234567890); 
INSERT INTO Table1 VALUES(1234567890., 1234567890., 1234567890.); 
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 
相關問題