Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将精度传递给python';格式法_Python_String Formatting - Fatal编程技术网

将精度传递给python';格式法

将精度传递给python';格式法,python,string-formatting,Python,String Formatting,我有一个变量,我需要根据不同的情况使用不同的精度来编写,有时我需要两位小数,有时甚至更多 最近我一直在尝试使用这个方法,而不是%操作符,但是我不知道如何做这个看起来很简单的事情 这里有一个MWE: # Some variable. a=5.2365548 # Define two precisions. x, y = 2, 5 # Print 'a' with different precisions. print 'The variable equals: {:.xf}'.format(a)

我有一个变量,我需要根据不同的情况使用不同的精度来编写,有时我需要两位小数,有时甚至更多

最近我一直在尝试使用这个方法,而不是
%
操作符,但是我不知道如何做这个看起来很简单的事情

这里有一个MWE:

# Some variable.
a=5.2365548
# Define two precisions.
x, y = 2, 5
# Print 'a' with different precisions.
print 'The variable equals: {:.xf}'.format(a)
print 'The variable equals: {:.yf}'.format(a)
理想情况下,每种情况下都会返回:

The variable equals: 5.24
The variable equals: 5.23655
当然,使用
:.xf
不起作用,但我相信它显示了我的需要

>>> print '{:.{prec}f}'.format(12.345, prec=2)
12.35
>>> print '{:.{prec}f}'.format(12.345, prec=1)
12.3