Skip to content

Commit

Permalink
Fix a bug with F to K conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
yulits committed Feb 8, 2024
1 parent 4f9e074 commit c26459b
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
10 changes: 6 additions & 4 deletions src/corva_unit_converter/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,6 @@ def convert(self, unit_from: str, unit_to: str, # noqa: CCR001, CFQ004
result = value * origin["unit"]["to_anchor"]

# for some units it's a simple shift (e.g. C to K)
if "anchor_shift" in destination["unit"]:
result += destination["unit"]["anchor_shift"]

if "anchor_shift" in origin["unit"]:
result -= origin["unit"]["anchor_shift"]

Expand All @@ -87,10 +84,15 @@ def convert(self, unit_from: str, unit_to: str, # noqa: CCR001, CFQ004
# Convert through transformation
transform = measures[origin["measure"]]["_anchors"][origin["system"]].get("transform")
if transform and callable(transform):
return transform(result)
result = transform(result)

# Convert through the anchor ratio
result *= measures[origin["measure"]]["_anchors"][origin["system"]]["ratio"]

# Apply shift after transformation for F to K
if "anchor_shift" in destination["unit"]:
result += destination["unit"]["anchor_shift"]

# Convert to another unit inside the destination system
return result / destination["unit"]["to_anchor"]

Expand Down
6 changes: 4 additions & 2 deletions src/corva_unit_converter/definitions/temperature.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,13 @@
"_anchors": {
"metric": {
"unit": "C",
"transform": lambda c: c / (5 / 9) + 32
"transform": lambda c: c / (5 / 9) + 32,
"ratio": 1
},
"imperial": {
"unit": "F",
"transform": lambda f: (f - 32) * (5 / 9)
"transform": lambda f: (f - 32) * (5 / 9),
"ratio": 1
}
}
}
2 changes: 2 additions & 0 deletions tests/test_temperature.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
{"from": "F", "amount": 32, "to": "C", "expected": 0},
{"from": "K", "amount": 0, "to": "C", "expected": -273.15},
{"from": "C", "amount": 0, "to": "K", "expected": 273.15},
{"from": "F", "amount": 32, "to": "K", "expected": 273.15},
{"from": "K", "amount": 0, "to": "F", "expected": -459.67},
]


Expand Down

0 comments on commit c26459b

Please sign in to comment.