0

I want to work with 3 digits after the decimal point in Python. What is the relevant setting to modify ?

I want that 1.0 / 3 would return 0.333, and not 0.3333333333333333 like it is the case in my Jupyter Notebook, using python 2.7.11 and Anaconda 4.0.0.

In my research, I heard about the Decimal class, but I don't want to use Decimal(x) in my code every time I display a float, neither the string formating or the round function, though I use it for the time being (because I don't want to use it every time).

I think there is a general solution, a setting computed only once.

salsa_man
  • 97
  • 1
  • 4
  • If the results are coming from numpy, you can use [numpy.set_printoptions](http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html). – Mephy Aug 05 '16 at 12:57
  • Is this just for printing? If so, you could concievable subclass the `float`, like [here](http://stackoverflow.com/questions/1566936/easy-pretty-printing-of-floats-in-python). Having said that, this _might_ be a duplicate. – Nelewout Aug 05 '16 at 13:27

2 Answers2

0

use numpy and try this;

round(1.0/3, 3)

or

>>> 1.0/3
0.3333333333333333

>>> '{:0.3f}'.format(1.0/3)
'0.333'
Mustafa DOGRU
  • 3,994
  • 1
  • 16
  • 24
  • The OP said very clearly that he wants something that will do the rounding automatically so that all floats are rounded. He explicitly said that he currently uses the `round ` function, but he doesn't like it because he needs to call it for each number. If the question were simply "How do I round a number to three decimal places", it would be a duplicate of many others. – zondo Aug 05 '16 at 13:18
0

There is no "one-time" solution to your problem. And I think that your approach might be a little misguided.

I suppose that your interaction with Jupyter or Ipython has lead you to the conclusion that python is quite handy as a numerical calculator. Unfortunately both of the aforementioned programs are just wrappers or REPL programs and in the background come with the full programming language flexibility that Python offers.

lesingerouge
  • 1,160
  • 7
  • 14