Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
Colin-Fredericks authored Nov 19, 2024
2 parents 9917c1c + 9a69f6b commit 7cbc046
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
19 changes: 10 additions & 9 deletions calc/calc.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
}

SUFFIXES = {
'%': 0.01,
'%': lambda x: x * 0.01,
}


Expand Down Expand Up @@ -112,24 +112,25 @@ def lower_dict(input_dict):

def super_float(text):
"""
Like float, but with SI extensions. 1k goes to 1000.
Evaluate suffixes if applicable and apply float.
"""
if text[-1] in SUFFIXES:
return float(text[:-1]) * SUFFIXES[text[-1]]
else:
return float(text)
func = SUFFIXES[text[-1]]
return func(float(text[:-1]))


def eval_number(parse_result):
"""
Create a float out of its string parts.
Returns an int or a float from string parts.
Calls super_float above for suffix evaluation.
e.g. [ '7.13', 'e', '3' ] -> 7130
Calls super_float above.
"""
if parse_result[-1] in SUFFIXES:
return super_float("".join(parse_result))

for item in parse_result:
if "." in item or "e" in item or "E" in item:
return super_float("".join(parse_result))
return float("".join(parse_result))

return int("".join(parse_result))

Expand Down
6 changes: 5 additions & 1 deletion tests/test_calc.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,11 @@ def test_si_suffix(self):
For instance '%' stand for 1/100th so '1%' should be 0.01
"""
test_mapping = [
('4.2%', 0.042)
('4.2%', 0.042),
('1%', 0.01),
('0.5%', 0.005),
('70%', 0.7),
('-50%', -0.5)
]

for (expr, answer) in test_mapping:
Expand Down

0 comments on commit 7cbc046

Please sign in to comment.