iT邦幫忙

3

[MS SQL]為什麼real轉decimal(38,8)會多出莫明的小數

drop table #tmp
create table #tmp
(
 c1 real
)
insert into  #tmp
select 56.08
select cast(c1 as decimal(38,8)  ) from #tmp

存入56.08
撈出來卻是56.08000183

56.8的科學記號為5.6080000E+01 但這樣為什麼會變成56.08000183

https://ithelp.ithome.com.tw/upload/images/20180607/20106764Yaw9CTXY3m.png
為什麼會這樣呢?

它是怎麼用01的方式存在DB裡呢?

#decimal point to two's complement

圓頭人 iT邦研究生 5 級 ‧ 2018-06-07 16:30:24 檢舉
找到了,謝謝各位大大的幫忙~

56.8 這樣轉成10101 儲進去(Decimal to IEEE 754 Floating Point Representation)
https://www.youtube.com/watch?v=8afbTaA-gOQ

然後再這樣被讀出來(EEE 754 Floating Point Representation to its Decimal Equivalent)
https://www.youtube.com/watch?v=LXF-wcoeT0o

因為小數點會被用2^-次方的方式被save,所以會有誤差.
0.3 = 0100 1100 1100 1100 1100 1100 1100 1100 1100.........
漂亮,謝謝說明。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

4
richardsuma
iT邦大師 1 級 ‧ 2018-06-07 11:12:33
最佳解答

請參考 隱含數值轉換表、明確數值轉換表
http://program-language-ll.blogspot.com/2017/04/blog-post_91.html
https://ithelp.ithome.com.tw/upload/images/20180607/20001981DLkZojM6R6.png

1
純真的人
iT邦大師 1 級 ‧ 2018-06-07 11:13:03

畢竟是近似值~如果可以縮小數點~你調整到小數第2位就好了@@

declare @tmp table
(
 c1 real
)
insert into  @tmp
select 56.08
select cast(c1 as decimal(38,2)  ) 
,cast(c1 as decimal(38,8)  )
,cast(c1 as decimal(38,25)  )
from @tmp

https://ithelp.ithome.com.tw/upload/images/20180607/20061369ggZqVROVar.png

我要發表回答

立即登入回答