Skip to content

Commit

Permalink
Merge pull request #54 from WildernessLabs/bug/temp-convert
Browse files Browse the repository at this point in the history
fix temperature conversion
  • Loading branch information
adrianstevens authored Mar 8, 2024
2 parents 5790d89 + 3825edc commit ca8094f
Showing 1 changed file with 35 additions and 27 deletions.
62 changes: 35 additions & 27 deletions Source/Meadow.Units/Conversions/TempConversions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,44 @@ namespace Meadow.Units.Conversions
{
internal static class TempConversions
{
// To Base (`C°`)
public static Func<double, double> FToC = (value) => (value - 32D) * (5D / 9D);
public static Func<double, double> KToC = (value) => value - 273.15D;
public static Func<double, double> FToC = (value) => (value - 32d) * (5d / 9d);
public static Func<double, double> KToC = (value) => value - 273.15d;
public static Func<double, double> CToF = (value) => value * (9d / 5d) + 32d;
public static Func<double, double> CToK = (value) => value + 273.15d;
public static Func<double, double> FToK = (value) => FToC(value) + 273.15d;
public static Func<double, double> KToF = (value) => CToF(value - 273.15);

// From Base
public static Func<double, double> CToF = (value) => value * (9D / 5D) + 32D;
public static Func<double, double> CToK = (value) => value + 273.15D;

public static double Convert(double value, Temperature.UnitType from, Temperature.UnitType to)
{
if (from == to) { return value; }

public static double Convert(double value, Temperature.UnitType from, Temperature.UnitType to)
{
if (from == to) { return value; }

if (from == Temperature.UnitType.Celsius && to == Temperature.UnitType.Fahrenheit) {
return CToK(value);
}
if (from == Temperature.UnitType.Fahrenheit && to == Temperature.UnitType.Celsius) {

switch (from)
{
case Temperature.UnitType.Celsius:
return to switch
{
Temperature.UnitType.Kelvin => CToK(value),
Temperature.UnitType.Fahrenheit => CToF(value),
_ => value
};
case Temperature.UnitType.Fahrenheit:
return to switch
{
Temperature.UnitType.Kelvin => FToK(value),
Temperature.UnitType.Celsius => FToC(value),
_ => value
};
case Temperature.UnitType.Kelvin:
return to switch
{
Temperature.UnitType.Fahrenheit => KToF(value),
Temperature.UnitType.Celsius => KToC(value),
_ => value
};
}

return value * temperatureConversions[(int)to] / temperatureConversions[(int)from];
}

//must align to enum
private static readonly double[] temperatureConversions =
{
1,//Celsius,
-32*(5D/9D),//Fahrenheit, // NO WAY TO GET THIS TO WORK?
//(9D / 5D) + 32D,
273.15D//Kelvin,
};
}
throw new NotSupportedException();
}
}
}

0 comments on commit ca8094f

Please sign in to comment.