My question is language independent. I want to write a simple unit convertor program. There are conversion types and according to the types there are units. For instance, if we take Length as conversion type then there’ll be Meter,Inch,Foot,Kilometer,Mile and so on. Imagine there are two dropdown boxes- one’s direction is from and the other’s is to. And there’s a textbox below each dropdown boxes. Simply when I choose Inch on the left handside and Mile on the right and type any number in either textboxes I want the equivalent to appear in the other textbox. Just like any normal unit conversion app.Now I’m very confused about this. Is just writing a long code with if…else if the only way of doing this? What way would you professionals follow?
My question is language independent. I want to write a simple unit convertor program.
Share
Use a general calculating unit, e.g. meter. Say you use meters to calculate everything, the user chooses ‘inch to foot’. Then you have to calculate the first unit into meters and meters again to mile. This way you only have to implement the scaling factors x for meter->unit (you can accomplish meter<-unit by using 1/x).
So if you have two dropdown boxes and a list of conversions meter->toUnit(unit), which converts a single meter to the corresponding value of the second unit, then you just have to use
EDIT: To ensure the numerical stability I recommend you to use a integer value and a very small reference unit (for example mili- or even micrometers). See comment.