根据python中的变量限制小数

时间:2015-02-04 18:45:38

标签: python decimal

我正在尝试编写一个程序,将golden ratio返回到小数位数限制。 到目前为止我所拥有的是:

def gr(n):
    a, b = 0, 1
    for x in range(0, n):
        a, b = b, a+b
    else:
        return(a)

    decimals = int(input("What amount of decimals do you want to see of the golden ratio?"))
    ratio = gr(41)/gr(40)
    print(format(ratio, '2f'))

问题是我找不到将ratio格式化为decimals中的数字的方法。

2 个答案:

答案 0 :(得分:0)

将precision / decimals变量传递给str.format:

decimals = int(input("What amount of decimals do you want to see of the golden ratio?"))
ratio = gr(41)/gr(40)
print("{:.{}f}".format(ratio,decimals))

示例:

In [3]: decimals = int(input("What amount of decimals do you want to see of the golden ratio?"))
What amount of decimals do you want to see of the golden ratio?5

In [4]: ratio = gr(41)/gr(40)

In [5]: print("{:.{}f}".format(ratio,decimals))
1.61803

答案 1 :(得分:-1)

以下是您尝试做的替代方案:

print(round(ratio, 2))

上面的代码段会将值ratio四舍五入到小数点后两位。所以要以十进制的整数表示,你可以这样做:

print(round(ratio, decimals))