Reputation: 1150
I try to get the removed part of the math.trunc
function.
Or a function supports this request.
import math
number = 1.9
newnumber, removed = math.trunc(number)
I need the number = 1
and also the removed 0.9
So basicly i need the integer and the removed float.
Obove example will not work :/ Any suggestions ?
Upvotes: 1
Views: 262
Reputation: 3515
For a starting point, use modulus 1 get the removed part.
def truncate(n):
return math.trunc(n), n % 1
Then you want to consider how negative numbers are handled. Do they return a positive ‘removed’ value?
This method won’t work for negative numbers, instead you can subtract the truncates number from the original:
t = math.trunc(n)
return t, n - t
Upvotes: 1
Reputation: 3037
If you use modf you can flip the order of your variables and get the result you want.
import math
number = 1.9
removed, newnumber = math.modf(number)
Upvotes: 3
Reputation: 36662
You need to keep a handle on the truncated number, and subtract it from the original number:
import math
number = 1.9
truncated = math.trunc(number)
print(truncated, number - truncated)
Upvotes: 3