2013-04-08 120 views
5

我在Excel中有以下一組計算,我希望能夠在存儲過程中使用。SQL浮點精度限制爲6位數

的Excel

CellA: 45/448.2 = 0.100401606425703 
CellB: 1-CellA = 0.899598393574297 
CellC: 1-CellB = 0.100401606425703 
CellD: CellC * 448.2 = 45.000000000000000 

在SQL我做了以下內容:

declare @a decimal(18,15) = 45/448.2 
declare @b decimal(18,15) = [email protected] 
declare @c decimal(18,15) = [email protected] 
declare @d decimal(18,15) = @c * 448.2 

我也試圖在一行

declare @e decimal(18,15) = (1-(1-(45/448.2)))*448.2 

運行計算時,我返回值SQL給我以下內容:

@a: 0.100401000000000 
@b: 0.899599000000000 
@c: 0.100401000000000 
@d: 44.999728200000000 

@e: 44.999728200000000 

我試過調整SQL中小數的精度,但是我沒有任何區別,它只返回小數的前6位數。

運行公式時,Excel是否做了任何優化?

任何想法?

+0

試試,說,'選擇45/CAST(448.2 AS DECIMAL(18,1))''。 [這裏的鏈接](http://stackoverflow.com/a/5385417/73226)告訴你分區結果數據類型的規則。 – 2013-04-08 16:03:43

+0

@MartinSmith確實給了我一個更完整的@a小數,儘管我的回答是45.000000000000085你能解釋爲什麼嗎? – ScampDoodle 2013-04-08 16:07:28

+0

這是從前面的答案,我懶得重現上面的兩個鏈接解釋。 e1/e2給出p = p1-s1 + s2 + max(6,s1 + p2 + 1),s = max(6,s1 + p2 + 1)'。如果'p'將是'> 38'然後's'被截斷在''6 – 2013-04-08 16:09:44

回答

7

即使只是你的第一行就足以說明問題:

declare @a decimal(18,15) = 45/448.2 
print @a 

--------------------------------------- 
0.100401000000000 

這是因爲數據類型。當你說

​​

是(每the documentation)解釋爲類型decimal,並also per the documentation恆定,

在Transact-SQL語句,帶有小數點的常量是 自動轉換爲數字數據值,使用必要的精度和標度的最小值 。例如,恆定12.345是 轉換成一個數字值爲5的精度和3.

所以448.2decimal(4,3)刻度。 45integer,其當與decimalis treated as having precision of 10 and scale 0組合時。當我們把,the rules

Operation  Result precision      Result scale 
e1/e2  p1 - s1 + s2 + max(6, s1 + p2 + 1)  max(6, s1 + p2 + 1) 

在這種情況下給出10 - 3 + 0 + max(6, 0 + 3 + 1)結果的精度和規模max(6, 0 + 3 + 1),其中就出來136

6的結果比例是結果只有小數點後六位的原因。

解決這個問題的方法是在對它們採取行動之前讓你的操作數進入適當的類型;例如,這裏有兩種方式:

力被視爲浮點數字:

declare @a decimal(18,15) = 45/448.2e0 
select @a 

--------------------------------------- 
0.100401606425703 

明確提供一個小數規模:

declare @a decimal(18,15) = 45/cast(448.2 as decimal(18,10)) 
select @a 

--------------------------------------- 
0.100401606425703 
+0

這使我在正確的道路上,我不得不調整多少小數位,但最終這是正確的答案 – ScampDoodle 2013-04-09 10:13:44