Tuesday, September 8, 2009

Decimal vs Float (Single) or Double

When you need to deal with a number that is a fraction, what do you specify for its type? If you are like most programmers I know, you’ll reach for Float (Single if you are using VB) or Double.

If you are working with currency, though, this could get you into a lot of trouble.

Here’s why.

When you store a number into a float, you are not storing an exact number. This is because the number you are storing is an approximation of the number you entered. When you store a number, the integer portion of the number gets priority and the fractional part gets entered as close as is possible given the size of the type you are storing it as.

That is, a Double will be able to save the information more accurately than the Float, but neither of them will store the information precisely.

And that’s just storing a number we enter directly. What happens if we need to multiply or divide that number?

For simplicity, let’s just say we need to divide a dollar by three. How would that get stored accurately into a float or a double? The answer is that it won’t. It will store as many threes on the right side of the decimal as possible.

This is what the Decimal data type was created for. A decimal data type deals with the data more like we would if we were dealing with the problem with paper and pencil. In effect, a decimal data type is similar to an integer that has a decimal point.


taked from : http://blog.dmbcllc.com/2008/10/14/decimal-vs-float-single-or-double/

No comments: