Units of measurement conversion logic in C #

I add a function to my program in which the user can change his unit of measure at any time and ask the program to recalculate their input and output.

If the user inputs say 20 pounds for the item, then decides that he wants to work in kilograms instead, he can choose the option to do it at any time, and the program will recount his 20lb input to 9Kg. Then, if he decides that he would prefer to work in ounces, he will convert these 9Kg to 320oz, etc., etc.

What will be the most effective and efficient way? I'm struggling to figure out how to correctly implement the formula.

+5
source share
3 answers

( , ).

  • .
  • .
  • , .

. .

+14

(, ) / .

, .

, F # UoM, , - , ...

+4

, , Units, Units.Torque Units.Length.

If you create a class of type Units.Weight and have all the conversion factors as constant values ​​and possible units as an enumeration, you can simply call this class and convert it to the desired units. This is a very simple example of the system we use:

namespace Units
{
    class Weight
    {
        public enum WeightType
        {
            kg,
            lb
        }

        const double kgTolbs = 2.20462262;

        public static double Convert(double value, WeightType fromUnits, WeightType toUnits)
        {
            //Code here to convert units
        }
    }
}

With this structure you can convert to any type of device at any time.

0
source

All Articles