Use float or decimal for accounting application dollar amount?

Sql Servervb.netDatabase DesignCurrencyAccounting

Sql Server Problem Overview


We are rewriting our legacy accounting system in VB.NET and SQL Server. We brought in a new team of .NET/ SQL Programmers to do the rewrite. Most of the system is already completed with the dollar amounts using floats. The legacy system language, I programmed in, did not have a float, so I probably would have used a decimal.

What is your recommendation?

Should the float or decimal data type be used for dollar amounts?

What are some of the pros and cons for either?

One con mentioned in our daily scrum was you have to be careful when you calculate an amount that returns a result that is over two decimal positions. It sounds like you will have to round the amount to two decimal positions.

Another con is all displays and printed amounts have to have a format statement that shows two decimal positions. I noticed a few times where this was not done and the amounts did not look correct. (i.e. 10.2 or 10.2546)

A pro is the float-only approach takes up eight bytes on disk where the decimal would take up nine bytes (decimal 12,2).

Sql Server Solutions


Solution 1 - Sql Server

> Should Float or Decimal data type be used for dollar amounts?

The answer is easy. Never floats. NEVER!

Floats were according to IEEE 754 always binary, only the new standard IEEE 754R defined decimal formats. Many of the fractional binary parts can never equal the exact decimal representation.

Any binary number can be written as m/2^n (m, n positive integers), any decimal number as m/(2^n*5^n). As binaries lack the prime factor 5, all binary numbers can be exactly represented by decimals, but not vice versa.

0.3 = 3/(2^1 * 5^1) = 0.3

0.3 = [0.25/0.5] [0.25/0.375] [0.25/3.125] [0.2825/3.125]

          1/4         1/8         1/16          1/32

So you end up with a number either higher or lower than the given decimal number. Always.

Why does that matter? Rounding.

Normal rounding means 0..4 down, 5..9 up. So it does matter if the result is either 0.049999999999.... or 0.0500000000... You may know that it means 5 cent, but the the computer does not know that and rounds 0.4999... down (wrong) and 0.5000... up (right).

Given that the result of floating point computations always contain small error terms, the decision is pure luck. It gets hopeless if you want decimal round-to-even handling with binary numbers.

Unconvinced? You insist that in your account system everything is perfectly ok? Assets and liabilities equal? Ok, then take each of the given formatted numbers of each entry, parse them and sum them with an independent decimal system!

Compare that with the formatted sum. Oops, there is something wrong, isn't it?

> For that calculation, extreme accuracy and fidelity was required (we used Oracle's > FLOAT) so we could record the "billionth's of a penny" being accured.

It doesn't help against this error. Because all people automatically assume that the computer sums right, and practically no one checks independently.

Solution 2 - Sql Server

Solution 3 - Sql Server

First you should read [What Every Computer Scientist Should Know About Floating Point Arithmetic][1]. Then you should really consider using some type of [fixed point / arbitrary-precision number][2] package (e.g., Java BigNum or Python decimal module). Otherwise, you'll be in for a world of hurt. Then figure out if using the native SQL decimal type is enough.

Floats and doubles exist(ed) to expose the fast [x87 floating-point coprocessor][3] that is now pretty much obsolete. Don't use them if you care about the accuracy of the computations and/or don't fully compensate for their limitations.

[1]: http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.22.6768 "What Every Computer Scientist Should Know About Floating Point Arithmetic" [2]: http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic [3]: https://en.wikipedia.org/wiki/Intel_8087

Solution 4 - Sql Server

Just as an additional warning, SQL Server and the .NET framework use a different default algorithm for rounding. Make sure you check out the MidPointRounding parameter in Math.Round(). .NET framework uses bankers' rounding by default and SQL Server uses Symmetric Algorithmic Rounding. Check out the Wikipedia article here.

Solution 5 - Sql Server

Ask your accountants! They will frown upon you for using float. Like David Singer said, use float only if you don't care for accuracy. Although I would always be against it when it comes to money.

In accounting software is not acceptable a float. Use decimal with four decimal points.

Solution 6 - Sql Server

Floating points have unexpected irrational numbers.

For instance you can't store 1/3 as a decimal, it would be 0.3333333333... (and so on)

Floats are actually stored as a binary value and a power of 2 exponent.

So 1.5 is stored as 3 x 2 to the -1 (or 3/2)

Using these base-2 exponents create some odd irrational numbers, for instance:

Convert 1.1 to a float and then convert it back again, your result will be something like: 1.0999999999989

This is because the binary representation of 1.1 is actually 154811237190861 x 2^-47, more than a double can handle.

More about this issue on my blog, but basically, for storage, you're better off with decimals.

On Microsoft SQL server you have the money data type - this is usually best for financial storage. It is accurate to 4 decimal positions.

For calculations you have more of a problem - the inaccuracy is a tiny fraction, but put it into a power function and it quickly becomes significant.

However decimals aren't very good for any sort of maths - there's no native support for decimal powers, for instance.

Solution 7 - Sql Server

A bit of background here....

No number system can handle all real numbers accurately. All have their limitations, and this includes both the standard IEEE floating point and signed decimal. The IEEE floating point is more accurate per bit used, but that doesn't matter here.

Financial numbers are based on centuries of paper-and-pen practice, with associated conventions. They are reasonably accurate, but, more importantly, they're reproducible. Two accountants working with various numbers and rates should come up with the same number. Any room for discrepancy is room for fraud.

Therefore, for financial calculations, the right answer is whatever gives the same answer as a CPA who's good at arithmetic. This is decimal arithmetic, not IEEE floating point.

Solution 8 - Sql Server

Use SQL Server's decimal type.

Do not use money or float.

money uses four decimal places and is faster than using decimal, but suffers from some obvious and some not so obvious problems with rounding (see this connect issue).

Solution 9 - Sql Server

I'd recommend using 64-bit integers that store the whole thing in cents.

Solution 10 - Sql Server

Floats are not exact representations, precision issues are possible, for example when adding very large and very small values. That's why decimal types are recommended for currency, even though the precision issue may be sufficiently rare.

To clarify, the decimal 12,2 type will store those 14 digits exactly, whereas the float will not as it uses a binary representation internally. For example, 0.01 cannot be represented exactly by a floating point number - the closest representation is actually 0.0099999998

Solution 11 - Sql Server

The only reason to use Float for money is if you don't care about accurate answers.

Solution 12 - Sql Server

For a banking system I helped develop, I was responsible for the "interest accrual" part of the system. Each day, my code calculated how much interest had been accrued (earnt) on the balance that day.

For that calculation, extreme accuracy and fidelity was required (we used Oracle's FLOAT) so we could record the "billionth's of a penny" being accrued.

When it came to "capitalising" the interest (ie. paying the interest back into your account) the amount was rounded to the penny. The data type for the account balances was two decimal places. (In fact it was more complicated as it was a multi-currency system that could work in many decimal places - but we always rounded to the "penny" of that currency). Yes - there where "fractions" of loss and gain, but when the computers figures were actualised (money paid out or paid in) it was always REAL money values.

This satisfied the accountants, auditors and testers.

So, check with your customers. They will tell you their banking/accounting rules and practices.

Solution 13 - Sql Server

Even better than using decimals is using just plain old integers (or maybe some kind of bigint). This way you always have the highest accuracy possible, but the precision can be specified. For example the number 100 could mean 1.00, which is formatted like this:

int cents = num % 100;
int dollars = (num - cents) / 100;
printf("%d.%02d", dollars, cents);

If you like to have more precision, you can change the 100 to a bigger value, like: 10 ^ n, where n is the number of decimals.

Solution 14 - Sql Server

Another thing you should be aware of in accounting systems is that no one should have direct access to the tables. This means all access to the accounting system must be through stored procedures.

This is to prevent fraud, not just SQL injection attacks. An internal user who wants to commit fraud should not have the ability to directly change data in the database tables, ever. This is a critical internal control on your system.

Do you really want some disgruntled employee to go to the backend of your database and have it start writing them checks? Or hide that they approved an expense to an unauthorized vendor when they don't have approval authority? Only two people in your whole organization should be able to directly access data in your financial database, your database administrator (DBA) and his backup. If you have many DBAs, only two of them should have this access.

I mention this because if your programmers used float in an accounting system, likely they are completely unfamiliar with the idea of internal controls and did not consider them in their programming effort.

Solution 15 - Sql Server

You can always write something like a Money type for .NET.

Take a look at this article: A Money type for the CLR. The author did an excellent work in my opinion.

Solution 16 - Sql Server

I had been using SQL's money type for storing monetary values. Recently, I've had to work with a number of online payment systems and have noticed that some of them use integers for storing monetary values. In my current and new projects I've started using integers and I'm pretty content with this solution.

Solution 17 - Sql Server

Out of the 100 fractions n/100, where n is a natural number such that 0 <= n and n < 100, only four can be represented as floating point numbers. Take a look at the output of this C program:

#include <stdio.h>

int main()
{
	printf("Mapping 100 numbers between 0 and 1 ");
	printf("to their hexadecimal exponential form (HEF).\n");
	printf("Most of them do not equal their HEFs. That means ");
	printf("that their representations as floats ");
	printf("differ from their actual values.\n");
	double f = 0.01;
	int i;
	for (i = 0; i < 100; i++) {
		printf("%1.2f -> %a\n",f*i,f*i);
	}
	printf("Printing 128 'float-compatible' numbers ");
	printf("together with their HEFs for comparison.\n");
	f = 0x1p-7; // ==0.0071825
	for (i = 0; i < 0x80; i++) {
		printf("%1.7f -> %a\n",f*i,f*i);
	}
	return 0;
}

Solution 18 - Sql Server

Have you considered using the money-data type to store dollar-amounts?

Regarding the con that decimal takes up one more byte, I would say don't care about it. In 1 million rows you will only use 1 more MB and storage is very cheap these days.

Solution 19 - Sql Server

Whatever you do, you need to be careful of rounding errors. Calculate using a greater degree of precision than you display in.

Solution 20 - Sql Server

You will probably want to use some form of fixed point representation for currency values. You will also want to investigate banker's rounding (also known as "round half to even"). It avoids bias that exist in the usual "round half up" method.

Solution 21 - Sql Server

Your accountants will want to control how you round. Using float means that you'll be constantly rounding, usually with a FORMAT() type statement, which isn't the way you want to do it (use floor / ceiling instead).

You have currency datatypes (money, smallmoney), which should be used instead of float or real. Storing decimal (12,2) will eliminate your roundings, but will also eliminate them during intermediate steps - which really isn't what you'll want at all in a financial application.

Solution 22 - Sql Server

Always use Decimal. Float will give you inaccurate values due to rounding issues.

Solution 23 - Sql Server

Floating point numbers can only represent numbers that are a sum of negative multiples of the base - for binary floating point, of course, that's two.

There are only four decimal fractions representable precisely in binary floating point: 0, 0.25, 0.5 and 0.75. Everything else is an approximation, in the same way that 0.3333... is an approximation for 1/3 in decimal arithmetic.

Floating point is a good choice for computations where the scale of the result is what is important. It's a bad choice where you're trying to be accurate to some number of decimal places.

Solution 24 - Sql Server

This is an excellent article describing when to use float and decimal. Float stores an approximate value and decimal stores an exact value.

In summary, exact values like money should use decimal, and approximate values like scientific measurements should use float.

Here is an interesting example that shows that both float and decimal are capable of losing precision. When adding a number that is not an integer and then subtracting that same number float results in losing precision while decimal does not:

    DECLARE @Float1 float, @Float2 float, @Float3 float, @Float4 float; 
    SET @Float1 = 54; 
    SET @Float2 = 3.1; 
    SET @Float3 = 0 + @Float1 + @Float2; 
    SELECT @Float3 - @Float1 - @Float2 AS "Should be 0";

Should be 0 
---------------------- 
1.13797860024079E-15

When multiplying a non integer and dividing by that same number, decimals lose precision while floats do not.

DECLARE @Fixed1 decimal(8,4), @Fixed2 decimal(8,4), @Fixed3 decimal(8,4); 
SET @Fixed1 = 54; 
SET @Fixed2 = 0.03; 
SET @Fixed3 = 1 * @Fixed1 / @Fixed2; 
SELECT @Fixed3 / @Fixed1 * @Fixed2 AS "Should be 1";

Should be 1 
--------------------------------------- 
0.99999999999999900

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGerhard WeissView Question on Stackoverflow
Solution 1 - Sql ServerTSKView Answer on Stackoverflow
Solution 2 - Sql ServerNakilonView Answer on Stackoverflow
Solution 3 - Sql ServerRich SchulerView Answer on Stackoverflow
Solution 4 - Sql ServerDarrel MillerView Answer on Stackoverflow
Solution 5 - Sql ServerRicardo CView Answer on Stackoverflow
Solution 6 - Sql ServerKeithView Answer on Stackoverflow
Solution 7 - Sql ServerDavid ThornleyView Answer on Stackoverflow
Solution 8 - Sql ServerMitch WheatView Answer on Stackoverflow
Solution 9 - Sql ServerJoshuaView Answer on Stackoverflow
Solution 10 - Sql ServerNiallView Answer on Stackoverflow
Solution 11 - Sql ServerDavid SingerView Answer on Stackoverflow
Solution 12 - Sql ServerGuyView Answer on Stackoverflow
Solution 13 - Sql ServerPeter StuifzandView Answer on Stackoverflow
Solution 14 - Sql ServerHLGEMView Answer on Stackoverflow
Solution 15 - Sql ServerTomer PintelView Answer on Stackoverflow
Solution 16 - Sql ServerGeorgeView Answer on Stackoverflow
Solution 17 - Sql ServerLars BohlView Answer on Stackoverflow
Solution 18 - Sql ServerEspoView Answer on Stackoverflow
Solution 19 - Sql Server1800 INFORMATIONView Answer on Stackoverflow
Solution 20 - Sql Serveruser6931View Answer on Stackoverflow
Solution 21 - Sql ServerDavid T. MacknetView Answer on Stackoverflow
Solution 22 - Sql ServerRoel VlemmingsView Answer on Stackoverflow
Solution 23 - Sql ServerMike DimmickView Answer on Stackoverflow
Solution 24 - Sql ServerBrokeMyLegBikingView Answer on Stackoverflow