Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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

Decimal is mainly use for currency. While it would work, people might find it confusing. In this case I think float would be a better choice.

Decimal - it is the simplest, however any of mentined will do the job

If you want store the results using as little space as possible you could probably do something like this (pseudocode):

integer = ( sum(all_values) / all_values.count().float ) * 100;

This will give you the value 352 for an average of 3.52 so you can store it as an integer (byte would be big enough I guess), and just divide it by 100 when you want to display it.

On the other hand if you don't care about the storage of the average value, using float values is maybe faster. (Test both to see what's actually fastest on your system.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top