Avoid floating-point arithmetic if you need exact answers.

Rounding errors will haunt you forever.

When working with computers, one often sees the use of floating-point numbers. One may see an item for sale for 5.36 dollars or an interest rate of 3.475%. However, the way computers store floating-point numbers in memory can introduce small amounts of error in these representations. For example, the computer may store 5.36 as 5.3600000000000003197442.

These differences are tiny, but when an algorithm determines whether to round numbers up or down, those small errors can lead to unexpected results.

Typically, floating-point numbers are acceptable in scientific applications where programmers understand that every measurement is an estimate. But one should not use them in financial applications where users expect payments to be exact.
For financial applications, one should work with integer representations and avoid rounding errors. The Money pattern is an excellent example of a tool that developers should use in these situations.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: