ashim
ashim

Reputation: 25560

How can I reduce the number of digits after decimal point when writing floats to file?

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.

Upvotes: 6

Views: 38939

Answers (3)

Levon
Levon

Reputation: 143032

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.

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

Upvotes: 3

Skurmedel
Skurmedel

Reputation: 22149

You don't say which version, or really how you are doing it in, so I'm going to assume 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   '

Upvotes: 8

larsks
larsks

Reputation: 311713

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.

Upvotes: 13

Related Questions