Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use decimal, float or double for this simple math result?

I'm doing some really simple math and saving the result to a MS SQL2008 DB.

I'm averaging out the some numbers, which are byte values between 1<->5. I wish to record probably 2 decimal places only. I don't care about rounding for the 2nd decimal place (eg. a 1.155 == 1.5 or 1.6 .. i'm not too phased).

So .. should i store the average result as a float, decimal or double?

When i check what LINQ returns, it can return all three values!

Lastly, what would be the relevant SQL datatype field, also.

cheers!

like image 717
Pure.Krome Avatar asked Oct 14 '22 17:10

Pure.Krome


2 Answers

What you need is the DECIMAL datatype:

declare @val decimal(10,2)
select @val = 10.155
select @val

When you input values, you can either rely on the built in rounding, or explicitly decide which rounding you want:

select val = round(10.155, 2, 0) -- rounded
select val = round(10.155, 2, 1) -- truncated

Decimal (10,2) means that ten digits can be used, and that two of them are to be taken as being after the decimal point. i.e. The highest number that decimal(4,2) can contain is 99.99. Trying to set it to 100 will result in arithmetic overflow.

like image 142
Jonathan Avatar answered Oct 18 '22 13:10

Jonathan


I would choose Float over Double and probably Float over Decimal:. Id go for Floatalthough all should give the same result.

Have a look at these two pages for Floats & Decimals

like image 33
TK. Avatar answered Oct 18 '22 13:10

TK.