1

Let's say there is a database that persists transaction data , e.g transaction items list of sale invoices , in raw format. Something like this

InvoceId Item Price
1 Product-1 2.8592
1 Product-2 10.7559
1 Product-3 5.25

Data is exposed to other backend and frontend services by an API , let's call it API-A. All the UI components need to display rounded-off data with sum in the bottom.

Simplified version of the architecture looks like this:

enter image description here

The question is, should API-A take care of rounding-off and summation of data ? Such as, accepting some query string parameters to support rounding-off and summation. Or should each consumer in this architecture take care of rounding and summation separately ? and why?

0

1 Answer 1

4

Rounding isn't something you can undo. It's a lossy process. So if there is any chance you'll have a need to do the rounding differently (rounding comes in many styles) then do the rounding in the report. Not in the stored data.

Of course that assumes the data can be stored without rounding. Some numbers like π can't be. So when you store them as data (not symbols) you're storing errors as well. When you make those errors part of a calculation it's a good idea to track their potential impact and be sure they don't grow enough to become significant.

One lesson I learned the hard way was if you're going to sum up floats that have different exponents it's a good idea to sort them and add up the the smaller ones first. Otherwise the big ones eat the little ones because their significant bits don't line up.

But hopefully you're not doing anything as silly as representing decimal money with binary floats in the first place.

TL;DR Don't store rounding if you can help it. If you can't, be sure you're using the right kind of rounding for your domain. Make sure the calculations you do on that data can tolerate the error caused by that rounding.

3
  • paragraph 4 should be paragraph 1, in bold, impact font, <blink>
    – Ewan
    Jun 26, 2021 at 13:52
  • I think there is a misunderstanding. Data is stored raw(unrounded). The question is where to do the rounding ? At API-A? or each consumer of the API-A should take care of rounding/summation by itself.
    – naltun
    Jun 27, 2021 at 4:02
  • 1
    @BorisZolotov that amounts to the same thing since API-A is the only way to get this data. Jun 27, 2021 at 4:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.