将浮点数写入文件时,如何减少小数点后的位数?

时间:2021-02-08 17:08:11

In my program I am printing float numbers to file. There is high precision of these numbers so there are many digits after decimal point, i.e number 0.0433896882981. How can I reduce number of digits that I print into file? So I would print, say, 0.043 instead of 0.0433896882981.

在我的程序中,我将浮点数打印到文件。这些数字的精度很高,因此小数点后面有很多位数,即数字0.0433896882981。如何减少打印到文件中的位数?所以我会打印,比方说,0.043而不是0.0433896882981。

3 个解决方案

#1


8  

You can use basic string formatting, such as:

您可以使用基本字符串格式,例如:

>>> print '%.4f' % (2.2352341234)
2.2352

Here, the %.4f tells Python to limit the precision to four decimal places.

这里,%。4f告诉Python将精度限制为四位小数。

#2


8  

You don't say which version, or really how you are doing it in, so I'm going to assume 3.x.

你没有说出哪个版本,或者你是怎么做的,所以我假设是3.x.

str.format("{0:.3f}", pi) # use 3 digits of precision and float-formatting.

The format specifier generally looks like this:

格式说明符通常如下所示:

[[fill]align][sign][#][0][minimumwidth][.precision][type]

Other examples:

>>> str.format("{0:" ">10.5f}", 3.14159265)
'   3.14159'
>>> str.format("{0:0>10.5f}", 3.14159265)
'0003.14159'
>>> str.format("{0:<10.5f}", 3.14159265)
'3.14159   '

#3


2  

The number of digits after the decimal point can be specified with the following formatting directive below:

可以使用以下格式指令指定小数点后的位数:

In [15]: n = 0.0433896882981
In [16]: print '%.3f' % n

that yields:

0.043

The % f part indicates that you are printing a number with a decimal point, the .3 the numbers of digits after the decimal point.

%f部分表示您正在打印带小数点的数字,.3表示小数点后的位数。

Additional examples:

In [17]: print '%.1f' % n
0.0

In [18]: print '%.2f' % n
0.04

In [19]: print '%.4f' % n
0.0434

In [20]: print '%.5f' % n
0.04339

#1


8  

You can use basic string formatting, such as:

您可以使用基本字符串格式,例如:

>>> print '%.4f' % (2.2352341234)
2.2352

Here, the %.4f tells Python to limit the precision to four decimal places.

这里,%。4f告诉Python将精度限制为四位小数。

#2


8  

You don't say which version, or really how you are doing it in, so I'm going to assume 3.x.

你没有说出哪个版本,或者你是怎么做的,所以我假设是3.x.

str.format("{0:.3f}", pi) # use 3 digits of precision and float-formatting.

The format specifier generally looks like this:

格式说明符通常如下所示:

[[fill]align][sign][#][0][minimumwidth][.precision][type]

Other examples:

>>> str.format("{0:" ">10.5f}", 3.14159265)
'   3.14159'
>>> str.format("{0:0>10.5f}", 3.14159265)
'0003.14159'
>>> str.format("{0:<10.5f}", 3.14159265)
'3.14159   '

#3


2  

The number of digits after the decimal point can be specified with the following formatting directive below:

可以使用以下格式指令指定小数点后的位数:

In [15]: n = 0.0433896882981
In [16]: print '%.3f' % n

that yields:

0.043

The % f part indicates that you are printing a number with a decimal point, the .3 the numbers of digits after the decimal point.

%f部分表示您正在打印带小数点的数字,.3表示小数点后的位数。

Additional examples:

In [17]: print '%.1f' % n
0.0

In [18]: print '%.2f' % n
0.04

In [19]: print '%.4f' % n
0.0434

In [20]: print '%.5f' % n
0.04339