|
Wanted: Software Developers
If you are looking for your next project or full time job, fill out my contact form and click on "I am a software developer seeking a referral interview".
>> Talk to me
|
|
|
 |
 |
Integers vs. Floating Points for Currency
Talking point: When to use floating points and when not to
I once came across code that stored currency as a floating point. For example, $0.05 was stored as the floating point 0.0500000. It relied on the floating point math handler to keep a 100% precise number. This bothered me because if a floating point math engine had a personality, it wouldn't "care" whether that 0.0500000 ever turned in to a 0.0499999.
Floating points are designed for things that don’t require absolute precision. Never use floating points for things that require perfect precision. Always use floating points for graphical things, like positioning and scaling of on-screen objects. They work great for that. The user will never notice a fraction of a pixel of error, nor will that type of error break the code and produce a “wrong” result.
The solution is to always express money in terms of cents. 5 cents should always be stored as the integer 5. 5 dollars should always be stored as the integer 500. The problem is that some coders feel like they need to store data the way they think of it in their head, instead of how it is ideally represented in the computer.
Some languages have a currency data type for just this reason: The number is stored as an integer (important), and it quietly moves the decimal place over exactly 2 digits so you can reserve mental state of what is being expressed when you write the code. Best of both worlds.
And some languages have a fixed-decimal data type, where you specify in advance how many digits of precision you desire. The point is that all arithmetic is done with integers, but expressed with the decimal point moved for convenience. Internally this is totally different than using floating points; Internally the math operations are identical to using integers. This way you are guaranteed never to have roundoff errors unless you do something that requires more precision than what you have specified in advance.
The point is this: floating points are not reliable when there is a zero tolerence for error, such as when money is involved. Only convert to dollars and cents at the last minute just before the number is displayed to the user. Why subject yourself to these complex roundoff problems when it’s not necessary? Integers have none of these problems. My advice: Don’t use floating points for currency.
|