具有指定精度的舍入和修剪数字

2024-04-19 15:37:22 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个函数,它接受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"

Tags: and函数字符串format编码参数returndef
1条回答
网友
1楼 · 发布于 2024-04-19 15:37:22

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

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.

相关问题 更多 >