會有這發現主要也是,公司最近有一個需要判斷數字相減後的結果是否為某個數字。
我覺得一般認知就是很簡單的認定有小數點的就是用double的型態,然後就直接拿double數字做相減。
做了一個小測驗,如圖

這邊的判斷式會是true,我覺得是有時候寫程式的時候不會注意到的事情。
為什麼會發生這樣的事情? 要如何解決這個問題?
https://www.vbforums.com/showthread.php?726853-subtracting-decimals-what-am-i-missing-!
這邊都有做解釋,這篇剛好也有相同的問題就用原文來給大家看
Unfortunately they are not accurate, because they are basically designed to be fast (working with floating-point data is surprisingly slow, so a quicker method was created).
If you want accuracy for numbers with decimal places, use data types that give the accuracy (but are slower), such as Currency and Decimal.
簡單講就是如果有遇到這種需要較為"準確"的計算,那就必須改用decimal 來當型別。

在這邊一併附上測試畫面。