使用不断变化的“位”变量格式化小数

问题描述 投票:0回答:1

我正在尝试编写一个函数,该函数将根据传递到函数中的“places”参数来更改小数位数。 我最终使用了 if/else 语句,但这非常有限。

有没有办法直接将“places”变量实现到format方法中?

如果可能的话,我也希望它不要圆形。传入“0”和“3”将返回 0.000。

def decimal(num, places):
    if places == 1:
        print(f'{num:.1f}')
    elif places == 2:
        print(f'{num:.2f}')
    elif places == 3:
        print(f'{num:.3f}')
python formatting
1个回答
0
投票

def 小数(数字,位数): print(f"{num:.{places}f}")

据我了解,上述回复解决了您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.