M4cJunk13
M4cJunk13

Reputation: 429

Python Can't get the 2 decimal place value to work using the "round" or "format" methods

I've tried different methods in order to get this to work, but it's not changing the value as expected.

for i in Lev1_clean_text:
    l = word_tokenize(i)
    c = Counter(category for token in l for category in parse(token))
    key_percent = [(i, round(c[i], 2) / len(l) * 100) for i in c]
    print(key_percent)

I've also tried changing this line below, but it's still not giving me the desired effect.

key_percent = [(i, int('{:2}'.format(c[i])) / len(l) * 100) for i in c]

Desired effect:

[('Hedge', 19.23), ('Absolute', 7.69)]
[('Negative', 12.5), ('Curses', 12.50), ('Hedge', 12.50), ('Absolute', 8.33)]

This is what I'm getting:

[('Hedge', 19.230769230769234), ('Absolute', 7.6923076923076925)]
[('Negative', 12.5), ('Curses', 12.5), ('Hedge', 12.5), ('Absolute', 8.333333333333332)]

Upvotes: 0

Views: 77

Answers (2)

yakunsun
yakunsun

Reputation: 21

assume c[i] is 123.45123 and len(l) is 1234.

then round(c[i], 2) is 123.45

so round(c[i], 2) / len(l) is 123.45/1234,and the result is 0.10004051863857374

obvious your expression is fault!

the right expression is

round(c[i]/len(l)*100, 2)

Upvotes: 1

grovina
grovina

Reputation: 3077

You are only rounding c[i], whereas you should round the final number:

round(c[i] / len(l) * 100, 2)

Upvotes: 1

Related Questions