Automatic decimal rounding issue

tl;dr

Don't do calculations in SQL language

Longer

The result scale and precision is well defined here on MSDN. It isn't intuitive, really. However, in simple terms, precision is lost when the input scales are high because the result scales need to be dropped to 38 with a matching precision drop.

To confirm things

  • Your extra CAST in the first example simply add zeroes
  • The truncation happens as per my MSDN link (2nd example)
  • The 3rd example with constants has implied decimal values that are just enough (5,1) and 18,14).
    This means the result scale and precision have no truncation (see blow)

More on the 1st and 3rd cases..

The result scale for a division is max(6, s1 + p2 + 1):

  • First example, this is 77 which is dropped to 38. Precision is forced down similarly, subject to a minimum of 6 (see this)
  • Third example, this is 24 so precision does not need adjusted

You have some options

  • calculate in the client code eg .net
  • use CLR functions to do .net calculations
  • live with the loss of accuracy
  • use float and live with 15 significant figures as best

FInally, see this on SO https://stackoverflow.com/questions/423925/t-sql-decimal-division-accuracy/424052#424052