ConvertWeight
Short summary
This function can be used to convert weights from one physical weight unit into another. The value will change corresponding to the conversion.
Example:
10 g = 154,324 US grain = 0.35274 US ounces = 0.564382 US dram = 0.01 kg = 0.00220462 US pounds
Return: CNM_RecipeHandling.Weight: a copy of the given weight converted into the desired unit
- Return type: Weight
Parameters
| Name | Type | Comment | Kind |
|---|---|---|---|
| weightToConvert | Weight | the weight that should be converted | inout |
| convertTo | WeightUnit | the physical weight unit it should be converted to | input |
| resultPrefix | MetricPrefixes | the metrical prefix (for SI units) | input |
Code
Declaration
FUNCTION ConvertWeight : Weight
VAR_IN_OUT CONSTANT
(* the weight that should be converted *)
weightToConvert :Weight;
END_VAR
VAR_INPUT
(* the physical weight unit it should be converted to *)
convertTo :WeightUnit := WeightUnit.GRAM;
(* the metrical prefix (for SI units) *)
resultPrefix :MetricPrefixes := MetricPrefixes.NONE;
END_VAR
VAR
factor :LREAL;
exponent :INT := 1;
END_VAR
VAR CONSTANT
(* weight convertions related to gram: gram, ton, US grain, US dram, US ounce, US pound, US ton *)
WEIGTHS : ARRAY[WeightUnit.GRAM..WeightUnit.US_TON] OF LREAL := [1.0, 1.0E6, 64.79891E-3, 1.771845195, 28.349523125, 453.59237, 907.18474E3 ];
END_VAR
Implementation
factor := WEIGTHS[weightToConvert.unit] / WEIGTHS[convertTo];
exponent := weightToConvert.prefix - resultPrefix;
ConvertWeight.prefix := resultPrefix;
ConvertWeight.unit := convertTo;
IF CheckValueIsANumber(weightToConvert.value) THEN
ConvertWeight.value := weightToConvert.value * factor * FastPow10(exponent);
ELSE
ConvertWeight.value := weightToConvert.value;
END_IF