I have stupid math problem. In T-SQL
why are these two sums different:
select (34.3+17.5 + 13.5)/31.0*28.0 --= 58.9806280
select 34.3/31.0*28.0 + 17.5/31.0*28.0 + 13.5/31.0*28.0 --= 58.9806000
I have stupid math problem. In T-SQL
why are these two sums different:
select (34.3+17.5 + 13.5)/31.0*28.0 --= 58.9806280
select 34.3/31.0*28.0 + 17.5/31.0*28.0 + 13.5/31.0*28.0 --= 58.9806000
Calculation are done with the operator priority rule, and regarding the type of your numbers.
The first one select (34.3+17.5 + 13.5)/31.0*28.0
is done in 3 steps:
select (34.3 + 17.5 + 13.5) -- = 65.3
select 65.3 / 31.0 -- = 2.106451
select 2.106451 * 28.0 -- = 58.9806280
The second one is done this way:
select 34.3 / 31.0 -- = 1.106451
select 17.5 / 31.0 -- = 0.564516
select 13.5 / 31.0 -- = 0.435483
select 1.106451 * 28.0 -- = 30.9806280
select 0.564516 * 28.0 -- = 15.8064480
select 0.435483 * 28.0 -- = 12.1935240
select 30.9806280 + 15.8064480 + 12.1935240 -- = 58.9806000
And if you go deeper, take a look at this one too:
select cast(34.3 as float)/31.0*28.0 + 17.5/31.0*28.0 + 13.5/31.0*28.0
-- => 58,9806451332903
My english is not that good, and somebody else has already pointed out what you're asking for, so if you want to know why numbers are rounded that way, there are 2 great links that can help you: https://stackoverflow.com/a/424052/4584335 and https://msdn.microsoft.com/en-us/library/ms190476(SQL.90).aspx