Do not use doubles or floats for dollar amounts.

Fractions of a penny are not a real thing and lead to difficult bugs.

The two most common practices for monetary values are:

  • Storing everything as pennies, and then remembering to convert to dollars on display. This can also be tricky when doing calculations, as you need to always remember that these are penny values.
  • Use a Money class. This uses the Value Object pattern to restrict what kind of values a Money object can have. It also forces all calculations to be made with more purposeful intent.

Leave a Reply

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

You are commenting using your 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: