Fabian
Fabian

Reputation: 1150

Trunc a number and get removed value. Or cast to int?

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

Answers (3)

N Chauhan
N Chauhan

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

Hitobat
Hitobat

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

Reblochon Masque
Reblochon Masque

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

Related Questions