2

My team is developing a web application, where we have in the requirements to display the data in multiple unit which is set by the end user.

Where should we write down the unit conversion logic, on front-end side or back-end side.

What is the good approach of doing the data conversion?

  1. We should perform on the front end side
  2. Can be performed on back end side:

    • We can save multiple data unit in the Database
    • We can apply conversion formula on API side.
  • A derivation of SI units (m, s, km, W, ...)? Packaging quantities (small container, card box XYZ, ...)? One can easily store Quantity+Unit in the database, do calculatory conversions based on Unit+Factor+BaseUnit from the database. No problem with respect to efficiency. – Joop Eggen May 6 at 9:16
  • @JoopEggen, We save data in SI units in db, what is the correct way to do that conversion, it should be done on front end side or backend side or should we save SI and Imperial both value in the db. – aman kumar May 6 at 9:20
  • Ahh, imperial values. If SI values are in the DB, for imperial goods there will be rounding errors. If for one customer the values are in SI, for another in IV, then you still have 2 kinds of invoices, so database seems the best option. – Joop Eggen May 6 at 9:33
  • I'd have a table dedicated towards how to convert one unit to another, and on application startup, I'd load it all up into a handler utility class. From there, converting to/from units is trivial throughout your program. If conversion isn't possible, it is because you lack the proper conversion in your table (I remind you if you have conversion from yards to feet, and feet to inches, you also have yards to inches). – Neil May 8 at 6:26
9

Keep consistent units within your system, and only convert to the user's preferred format at the boundaries of your system. The “boundary” doesn't necessarily mean front-end or back-end, this is more about how you structure the logic in your application. A classic MVC application would convert incoming data in the controllers, and outgoing data in the views.

Do not store the data in multiple formats in the database. This makes it so much harder to keep the various versions of the data consistent, and will make queries more complicated. Internally, your system should define a single authoritative data model.

  • If we're talking about display and it's a web-app, why not just use JS to render data to whatever output we need? Especially if the conversion is rather trivial, a small set of functions can be written to achieve that. – coolpasta May 8 at 7:02
  • @coolpasta Exactly, a bit of JS can be the perfect solution to a website. Where this conversion happens is not relevant, as long as it isn't in the business logic. – amon May 8 at 7:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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