# round() doesn”t seem to be rounding properly

| |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

The documentation for the round() function states that you pass it a number, and the positions past the decimal to round. Thus it should do this:

``````n = 5.59
round(n, 1) # 5.6
``````

But, in actuality, good old floating point weirdness creeps in and you get:

``````5.5999999999999996
``````

For the purposes of UI, I need to display `5.6`. I poked around the Internet and found some documentation that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I"ve tried. See here also.

Short of creating my own round library, is there any way around this?

👻 Read also: what is the best laptop for engineering students?

## round() doesn"t seem to be rounding properly around: Questions

Removing white space around a saved image in matplotlib

I need to take an image and save it after some process. The figure looks fine when I display it, but after saving the figure, I got some white space around the saved image. I have tried the `"tight"` option for `savefig` method, did not work either. The code:

``````  import matplotlib.image as mpimg
import matplotlib.pyplot as plt

fig = plt.figure(1)
plt.imshow(img)

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig("1.png", bbox_inches=extent)

plt.axis("off")
plt.show()
``````

I am trying to draw a basic graph by using NetworkX on a figure and save it. I realized that without a graph it works, but when added a graph I get white space around the saved image;

``````import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
pos = {1:[100,120], 2:[200,300], 3:[50,75]}

fig = plt.figure(1)
plt.imshow(img)

nx.draw(G, pos=pos)

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig("1.png", bbox_inches = extent)

plt.axis("off")
plt.show()
``````
228

You can remove the white space padding by setting `bbox_inches="tight"` in `savefig`:

``````plt.savefig("test.png",bbox_inches="tight")
``````

You"ll have to put the argument to `bbox_inches` as a string, perhaps this is why it didn"t work earlier for you.

Possible duplicates:

Matplotlib plots: removing axis, legends and white spaces

How to set the margins for a matplotlib figure?

Reduce left and right margins in matplotlib plot

228

I cannot claim I know exactly why or how my “solution” works, but this is what I had to do when I wanted to plot the outline of a couple of aerofoil sections — without white margins — to a PDF file. (Note that I used matplotlib inside an IPython notebook, with the -pylab flag.)

``````plt.gca().set_axis_off()
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.margins(0,0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.savefig("filename.pdf", bbox_inches = "tight",
``````

I have tried to deactivate different parts of this, but this always lead to a white margin somewhere. You may even have modify this to keep fat lines near the limits of the figure from being shaved by the lack of margins.

How to print number with commas as thousands separators?

I am trying to print an integer in Python 2.6.1 with commas as thousands separators. For example, I want to show the number `1234567` as `1,234,567`. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.

It does not need to be locale-specific to decide between periods and commas. I would prefer something as simple as reasonably possible.

929

### Locale unaware

``````"{:,}".format(value)  # For Python ‚â•2.7
f"{value:,}"  # For Python ‚â•3.6
``````

### Locale aware

``````import locale
locale.setlocale(locale.LC_ALL, "")  # Use "" for auto, or force e.g. to "en_US.UTF-8"

"{:n}".format(value)  # For Python ‚â•2.7
f"{value:n}"  # For Python ‚â•3.6
``````

### Reference

The `","` option signals the use of a comma for a thousands separator. For a locale aware separator, use the `"n"` integer presentation type instead.

929

I got this to work:

``````>>> import locale
>>> locale.setlocale(locale.LC_ALL, "en_US")
"en_US"
>>> locale.format("%d", 1255000, grouping=True)
"1,255,000"
``````

Sure, you don"t need internationalization support, but it"s clear, concise, and uses a built-in library.

P.S. That "%d" is the usual %-style formatter. You can have only one formatter, but it can be whatever you need in terms of field width and precision settings.

P.P.S. If you can"t get `locale` to work, I"d suggest a modified version of Mark"s answer:

``````def intWithCommas(x):
if type(x) not in [type(0), type(0L)]:
raise TypeError("Parameter must be an integer.")
if x < 0:
return "-" + intWithCommas(-x)
result = ""
while x >= 1000:
x, r = divmod(x, 1000)
result = ",%03d%s" % (r, result)
return "%d%s" % (x, result)
``````

Recursion is useful for the negative case, but one recursion per comma seems a bit excessive to me.

How would you make a comma-separated string from a list of strings? By mweerden

What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, `["a", "b", "c"]` to `"a,b,c"`? (The cases `["s"]` and `[]` should be mapped to `"s"` and `""`, respectively.)

I usually end up using something like `"".join(map(lambda x: x+",",l))[:-1]`, but also feeling somewhat unsatisfied.

612

``````my_list = ["a", "b", "c", "d"]
my_string = ",".join(my_list)
``````
``````"a,b,c,d"
``````

This won"t work if the list contains integers

And if the list contains non-string types (such as integers, floats, bools, None) then do:

``````my_string = ",".join(map(str, my_list))
``````

## Shop Learn programming in R: courses

\$ Best Python online courses for 2022

\$ Best laptop for Fortnite

\$ Best laptop for Excel

\$ Best laptop for Solidworks

\$ Best laptop for Roblox

\$ Best computer for crypto mining

\$ Best laptop for Sims 4

\$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

NUMPYNUMPY

How to convert Nonetype to int or string?

NUMPYNUMPY

How to specify multiple return types using type-hints

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

## Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method