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

跟風遠走 提交于 2019-12-08 21:25:30

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)

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
Asha Anandan

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
gañañufla

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!