ayat ullah sony
ayat ullah sony

Reputation: 2023

How to get rid of additional floating numbers in python subtraction?

def function():
    n=123.456
    x=int(n)
    y=n-int(n)
    print(x,y)

result:

x= 123
y= 0.45600000000000307 

how to get exactly .456 without using library function, n can be any floating number

Upvotes: 0

Views: 1050

Answers (4)

gañañufla
gañañufla

Reputation: 562

Try with round(y,n), and n=3 its the numbers of decimals.

Upvotes: 0

Asha Anandan
Asha Anandan

Reputation: 56

You can use %f to round of the floating value to required digits.

def function(n):

    x = int(n)
    y = n-int(n)
    print(x,"%.2f" % y)

function(123.456)

Output:

123

0.456

Upvotes: 0

Emma
Emma

Reputation: 27723

You can also use the re module:

import re

def get_decimcal(n: float) -> float:
    return float(re.search(r'\.\d+', str(n)).group(0))

def get_decimcal_2(n: float) -> float:
    return float(re.findall(r'\.\d+', str(n))[0])

def get_int(n: float) -> int:
    return int(n)


print(get_decimcal(123.456))
print(get_decimcal_2(123.456))
print(get_int(123.456))

Output

0.456
0.456
123

Upvotes: 1

Ian
Ian

Reputation: 3898

If you know from the outset that the number of decimal places is 3, then:

y = round(n - int(n), 3)

If you don't know the number of decimal places, then you can work it out, as so:

y = round(n - int(n), str(n)[::-1].find('.'))

As furas pointed out, you can also use the decimal package:

from decimal import Decimal

n = Decimal('123.456') 
y = n - int(n)

Upvotes: 1

Related Questions