0

I am working on an app that deals with ecommerce sales orders. We use the money-rails gem.

Orders are imported from another system which may occasionally have numbers with partial cents. For example:

Order Line Item
quantity = 5
unit price = 1.29
discount = 0.064

In our database, our columns are integers and amounts are stored as cents. Unfortunately, when we calculate the subtotal of a line item using the imported values stored in our database, we end up getting rounded numbers because the integer column only stores whole numbers.

In the above example, we would calculate a subtotal of 5 x (129 - 6) which equals $6.15 but in reality it should really be 5 x (129 - 6.4) which equals $6.13.

When using the money-rails gem, what would be the best practice avoid these types of rounding errors? Should we convert our columns from integer to decimal? Or is there another method that works better?

Isaac Y
  • 660
  • 1
  • 9
  • 27
  • 2
    You either need to stop expecting fractions of cents to work, or you need to support fractions of cents. This has nothing to do with the `money-rails` gem, but rather is a question of how you want your application to work. – Jon Jun 30 '21 at 06:51
  • In that case is it reasonable to say we should store these figures as a decimal data-type? I was under the impression that money-rails prefers you to store as integers – Isaac Y Jul 01 '21 at 04:59
  • If you need to support fractions of cents, then you need to store them somehow. Either decide to how many decimal places and store them as integers to avoid rounding issues ... or go with floating point numbers and be very very careful with your tests. Just convert things back to cents before passing values to money-rails for display. You could just store millicents (0.001 cents) as an integer, and convert back to cents from there. – Jon Jul 01 '21 at 09:52

0 Answers0