Domanda

http://www.ozzu.com/programming-forum/mysql-storing-dollar-amounts-field-type-t106432.html

This forum seems to suggest you should store currency such as USD in its lowest common denominator ie: cents as a INT as opposed to a DECIMAL.

This seems somewhat silly to me. Anyone want to explain the reasoning for this especially why it's worth the time to code out formatting methods for the values?

Thanks.

È stato utile?

Soluzione

Strictly speaking, storing as cents is simpler and it models the real world. Do you really collect and pay out fractional amounts of a dollar (1.255), or do you pay in cents (125)? I bet you pay and collect in cents.

If you do deal with actual fractions, then use decimal, but try to avoid the repeating fractions.

Generally, in accounting, you have to account for every penny, so you'll be dealing with remainders either way you go. If you stick with integers (cents), you'll more easily account for every penny.

Altri suggerimenti

As other's have said the loss of acccuracy with floating points (not decimals), using an int if your data will fit can make a lot of sense. Formatting it for display / reporting is a trivial problem compared explaining to management that 8 decimal places doesn't imply an accurate value....

Don't even mention people using double, single and if anyone remembers it real interchangeable or wondering why if C = A - B then A may not equal C + B.

Same concept saved me a lot of heartache, by storing mass in kilos instead of tonnes to three decimal paces.

Ultimately it doesn't matter, unless you have a super huge database. I believe the efficiency of the engine to handle ints is faster then floating points. So it improves speed on large databases. I may be wrong, I never do that myself

DECIMAL itself is fine, but most programming languages don't support fixed-point arithmetic (only integer arithmetic and floating-point arithmetic), which means that your application will most likely have to use integers rather than floating-point values (since floating-point values cannot represent 12.34 exactly, and the round-trip can cause wrong results), so it's a bit of a pain to handle the conversions between application-integers and database-DECIMALs. But, as you note, you have to put in work to use the INTEGER approach as well, so if you prefer to put your work toward using DECIMAL, I think that's 100% reasonable.

Storing the currency in the DB is only (less than) half the job: You need to work with the amounts before and after. Int is a data type that is well understood by all relevant programming environments out there, fixed-point definitly is not.

So while your DB might add DECIMAL values correctly, your application might not (converting it to float).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top