Jed
Jed

Reputation: 43

how to limit the number of digit after the float with python 3?

In my program I have several calculations that produce float numbers as results. I would like to know if there's a general declaration in Python 3 that allows to limit all the floats in the program to let's say 8 digits, systematically ?

Thank you for your help !

# Create initial balance for user 1 and user 2.
bal_user1 = 21.82233503
bal_user2 = 5.27438039
# Calculate percentage of capital for each user
percent_capi_user2 = 100 * bal_user2 / ( bal_user1 + bal_user2)
percent_capi_user1 = 100 - percent_capi_user2
print("User 1 as " + str(percent_capi_user1) + (" % of the capital"))
print("User 2 as " + str(percent_capi_user2) + (" % of the capital"))

The output is :

User 1 as 80.53498253110413 % of the capital
User 2 as 19.465017468895866 % of the capital

I would like for example : 80.53498253 instead of 80.53498253110413 And since I'm doing several calculations later on in the program, I was wondering if there was a general declaration to put once at the beginning of the code. In order to avoid casting the right number of digits each time...

Upvotes: 2

Views: 545

Answers (1)

user8711334
user8711334

Reputation:

Well, buddy, I think I have just what you are looking for!

What you are looking for is the decimal module and the included Decimal class. Now, I am not going to go into it, because I am not that knowledgeful in it, but what I can do is point you in the right direction. In short, read the documentation here ( https://docs.python.org/3/library/decimal.html?highlight=decimal#module-decimal ), and look for decimal.getcontext().prec, which will allow you to, at least with Decimal objects, control their precision "globally".

Upvotes: 1

Related Questions