Python Forum
Is There a Better Way to Truncate Variables?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is There a Better Way to Truncate Variables?
#1
Hello everyone,

Newbie here, and I want to drop the decimal values on a calculated number in my application then multiply it by an integer and end up with an integer with no decimal. But for the life of me, I can't get it to work elegantly. I've waded through this forum and the Internet in search of a better solution but can't seem to find one. Does anyone know of a better way to do this? Here's my code:

portfolio_size = 20000

equity1 = math.trunc((portfolio_size / 6000) * 100)
equity2 = int((portfolio_size / 6000) * 100)
equity3 = portfolio_size / 6000
equity3 = int(equity3) * 100
equity4 = portfolio_size / 6000
equity4 = int(equity4 * 100)

print(f"equity1 solution = ", equity1)
print(f"equity2 solution = ", equity2)
print(f"equity3 solution = ", equity3)
print(f"equity4 solution = ", equity4)
Here's my output:

Output:
333 equity1 solution = 333 equity2 solution = 333 equity3 solution = 300 equity4 solution = 333
equity3 is the only solution that gives me what I want, but it's two lines of code and very clunky. Is there a function available that will do the job with just one line of code? Or is it possible to write code that will do it on one line?

Any assistance is greatly appreciated.
Reply
#2
Use integer division (//): equity = portfolio_size // 6000 * 100.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
ichabod801, I hadn't heard of 'integer division' before now. I used your code and it worked beautifully. So I did some reading on the topic and it's very cool. Thank you very much, again! More reputation to you my friend. Smile
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020