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

4

0
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

Marcy answered 4/11, 2019 at 4:35 Comment(2)
Does this answer your question? Is floating point math broken?Boadicea
it is natural for float numbers. You can try with standard module decimal if you need precise values - d = decimal.Decimal('123.456') print(d - int(d))Rebroadcast
A
1

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)
Anthropogenesis answered 4/11, 2019 at 4:41 Comment(0)
F
1

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
Fingerprint answered 4/11, 2019 at 4:55 Comment(0)
D
0

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

Deceive answered 4/11, 2019 at 4:41 Comment(0)
D
0

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
Damsel answered 4/11, 2019 at 5:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.