Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: evaluate integer percentage #114

Merged
merged 2 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 = {
jesperhodge marked this conversation as resolved.
Show resolved Hide resolved
'%': 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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would like to still see SI extensions mentioned and some example would also be helpful in the comment.

"""
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
Loading