python-3.x - 如何让算法自动以 "smart"方式循环

标签 python-3.x rounding

我想对代码中的数字进行四舍五入,但要以适应每个值的方式进行舍入。

例如,我想要返回舍入算法:

  • 0.999999 它应该返回 1
  • 0.0749999 它应该返回 0.075
  • 0.006599 它应该返回 0.0066 等等...

我事先不知道位数(这有点是我的问题)

我想用字符串来查找 9 在哪里(或数 0),但我想这需要付出很大的努力?

如果您知道有什么方法可以做到这一点(如果可能的话,无需高级库),我将不胜感激。

谢谢。

最佳答案

有点复杂。但是,它有效。请确保结果是您想要的。我想你可以理解如何从代码中对数字进行四舍五入。

def clear9(numstr):
    liststr = list(numstr)
    for index in range(len(liststr)-1,-1,-1):
        if liststr[index] == '.': continue
        if liststr[index] == '9': 
            liststr[index] = '0'
            if index == 0:
                liststr.insert(0, '1')
        else: 
            if index != len(liststr)-1:
                liststr[index] = str(int(liststr[index])+1)
            break
    numstr = ''
    for item in liststr:
        numstr += item
    return numstr

def myround(num):
    numstr = str(num)
    numstr = clear9(numstr)
    return float(numstr)


print (myround(9.05))
print (myround(9.999999))
print (myround(0.999999))
print (myround(0.0749999))
print (myround(0.006599))
print (myround(0.00659923))
print (myround(0.09659923))
print (myround(-0.00659923))
9.05
10.0
1.0
0.075
0.0066
0.00659923
0.09659923
-0.00659923

关于python-3.x - 如何让算法自动以 "smart"方式循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56264675/

相关文章:

python - 从元组列表中获取其元素之间差异最大的元组

python - 导入错误 : cannot import name 'Account' from 'O365' using Office 365 Project

python-3.x - 在 Google Colab 上安装 spaCy 3.0 的麻烦

python - 舍入小数的问题(python)

冷聚变 9 : Round to 2 decimals on avg() in QoQ

python - 如何在单独的进程中启动具有多个队列的多处理网络管理器

python - Python 中字典的严格比较

java - 如何对浮点值进行四舍五入,使其小数点后不包含 0

c - 将十六进制 printf 输出存储到变量

python - 整数除法四舍五入