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

a 夏天 提交于 2019-12-08 04:43:20

问题


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


回答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)



回答2:


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



回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/58687240/how-to-get-rid-of-additional-floating-numbers-in-python-subtraction

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