如何摆脱python减法中的额外浮点数? [英] How to get rid of additional floating numbers in python subtraction?

查看:57
本文介绍了如何摆脱python减法中的额外浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

结果:

x= 123
y= 0.45600000000000307 

如何在不使用库函数的情况下准确获取.456n 可以是任意浮点数

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

推荐答案

您也可以使用 re 模块:

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

输出

0.456
0.456
123

这篇关于如何摆脱python减法中的额外浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆