![]() |
Is There a Better Way to Truncate Variables? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Is There a Better Way to Truncate Variables? (/thread-23564.html) |
Is There a Better Way to Truncate Variables? - joew - Jan-05-2020 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: 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. RE: Is There a Better Way to Truncate Variables? - ichabod801 - Jan-05-2020 Use integer division (//): equity = portfolio_size // 6000 * 100 .
RE: Is There a Better Way to Truncate Variables? - joew - Jan-05-2020 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. ![]() |