How I avoid bugs when dealing with Percentage (%) values

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 backend system. My entire backend knows that values are divided by 100 before they’re stored. So whenever query retrieves it, it’s a decimal value.

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! So before backend returns the values, it should make sure it’s in correct format.

For example, User enters 20%. We store 0.2 in the database. We return 0.2. Frontend displays 20% again by multiplying it by 100.


Backend stores decimal

Backend returns decimal via API.

Frontend displays whole number (multiplying it by 100).

Frontend can keep the decimal in memory/storage if it needs to. But keeping display value separate

Frontend sends back to backend the decimal.

Backend validates and stores.

Download a free copy

Leave a comment

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