gpt4 book ai didi

python - 将 float 中的点向下移动

转载 作者:行者123 更新时间:2023-11-28 20:28:24 24 4
gpt4 key购买 nike

首先,感谢您的关注,我是这个网站的新手 ^^ 如果我做错了什么,请原谅...

我的 Python 代码有一个大问题...我是编程新手,也是 Python 新手。

我需要取一个 float 并将小数点向右移动,使其变成一个整数,比如取 60.27 得到 6027。

我使用的算法递归地乘以 num*10 直到 num%2==0,然后得到 int(num).

问题是,当我乘以(例如)602.47*10 它返回 6024.700000000001 并且它显然不起作用:-)

有什么方法可以修复它,或者任何其他技术或其他递归执行此操作的方法吗?我可以使用我需要的任何东西,但它必须是递归的:没有 forwhile...

感谢帮助!!我的第一语言不是英语,所以如果读起来有点困难,请原谅...

最佳答案

>>> str(60.27).translate(None, '.')
'6027'

使用 lstrip('0') 防止小数小​​于 1。


来自文档:

S.translate(table [,deletechars]) -> string

Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.

关于python - 将 float 中的点向下移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5463541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com