Avoiding Bugs when working with Percentage (%) values in your application

The idea is that if we have a proper understanding between frontend and the backend then many serious bugs can be avoided.

Let’s take VAT Rate as an example.

We have an application that displays percentage on frontend, for example 10%, 20%, 19.5%, 2%, 0.5% VAT etc.

Our job is to make sure there’s a contract between frontend/backend. In other words, make sure both sites understand what they’ll receive and what to send.

For example, a User could enter 20 (20% VAT).

To save this value I’d send it to backend as is without any manipulation.

My backend knows what to expect here. Before it’s stored in the database the RULE is to divide it by 100.

This is so I don’t have to divide it by 100 again and again everywhere in the system. My entire backend knows that values are divided by 100 before they’re stored. This is documented and everyone is aware of this.

Some people like to store values as is once validated. But it really depends on how they want to use it, often storing in the right format means you’re cutting down on steps later.

That’s the backend. We’re dealing with one format, and we know what that format is.

Now how do we deal with values on frontend?

Well, the frontend must know and expect to receive whatever it initially sent, if it sent 20% VAT it’ll get back 20, not 0.2! If it sent 0.9, it would receive 0.9!

This is because backend would always make sure the value is multiplied by 100 before it’s returned. (Reversed).

For example, User enters 20%. We store 0.2 in the database.

But if we need to return it back to the frontend, it must be converted back to 20. Last thing you want to do is return 0.2 to the frontend!

This is a simple contract that’ll make everyone’s lives easier if documented properly!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *