Posted over 9 years ago. Visible to the public. Repeats.

BigDecimal arithmetic in Ruby

Ruby comes with a class BigDecimal which you can use for arbitrary precision arithmetic. You should use BigDecimal instead of Float whenever you care about rounding errors, e.g. whenever you are dealing with money.

You should remember these two rules when working with BigDecimal values:

  • When you add or multiply a BigDecimal with another BigDecimal, the result will be a new BigDecimal with sufficient precision to represent the result. No rounding or clipping should occur in that operation.
  • When you add or multiply a BigDecimal with a Float, the result will be a Float. That means you just transitioned back into the land of random rounding errors.

Don't screw up your clean BigDecimal values by thoughtlessly multiplying them with a Float. For instance, this is a stupid idea:

VAT_RATE = 1.19 net = BigDecimal('12.3413') gross = net * VAT_RATE # oops, gross is now a Float

Do this instead:

VAT_RATE = BigDecimal('1.19') net = BigDecimal('12.3413') gross = net * VAT_RATE # gross is now a BigDecimal

ActiveRecord models represent MySQL's DECIMAL columns as BigDecimal attributes. Keep in mind that values assigned to such attributes might be clipped or rounded when the record is saved to the database.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Henning Koch
Last edit:
over 3 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more