Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

%precision 2 on Python

If I have this piece of code:

import csv

%precision 2

with open('blah.csv') as csvfile:
    blah = list(csv.DictReader(csvfile))

What does it means the %precision 2 line?

like image 490
AdN Avatar asked May 16 '18 16:05

AdN


People also ask

What is %Precision 2 in Python?

It sets the floating point to 2 decimal points.

What does %precision mean in Python?

Using “%”:- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming. Using format():- This is yet another way to format the string for setting precision.

How do you do 2 decimal places in Python?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.


2 Answers

This is an IPython magic. It controls how floats display:

>>> 1.2345
1.2345
>>> %precision 2
'%.2f'
>>> 1.2345
1.23

Documented here.

Note: It suggests your script was intended to be executed within an IPython runtime (such as a notebook). In a regular Python interpreter that will be a syntax error.

like image 177
wim Avatar answered Sep 21 '22 03:09

wim


This is to set a floating point precision for printing. It sets the floating point to 2 decimal points. This doesn't work in all interpreters though, but it does work in Jupyter-Notebook.

NB: Thanks to Chrisz for the point.

like image 35
Yadu Avatar answered Sep 19 '22 03:09

Yadu