gpt4 book ai didi

python - 以指定精度舍入和修整数字

转载 作者:行者123 更新时间:2023-11-28 21:55:39 26 4
gpt4 key购买 nike

假设我有一个函数,它接受一个 float 并返回一个转换为具有 2 位预定义精度的字符串:

def round_and_trim(x):
return "{0:.2f}".format(round(x,2))

它的工作原理如下:

x = 0.238498
y = round_and_trim(x)
y = "0.24"

我怎样才能让这个函数接受一个名为 precision 的参数,这样它就不会转换为硬编码的精度值 2,而是使用 precision 中的值?

例如

x = 0.238498
y = round_and_trim(x, precision=4)
y = "0.2385"

或:

x = 0.238498
y = round_and_trim(x, precision=3)
y = "0.238"

最佳答案

您可以嵌套替换字段,例如:

def round_and_trim(x, precision=2):
return "{0:.{prec}f}".format(round(x, precision), prec=precision)

因此,当 precision3 时,格式字符串实际上将变为 "{0:.3f}"

来自docs :

A *format_spec* field can also include nested replacement fields within it. These nested replacement fields can contain only a field name; conversion flags and format specifications are not allowed. The replacement fields within the *format_spec* are substituted before the *format_spec* string is interpreted. This allows the formatting of a value to be dynamically specified.

关于python - 以指定精度舍入和修整数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22547601/

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