Formatting Numbers in Python Cheat Sheet

<Blake†Codez />
3 min readFeb 22, 2021
Photo by Markus Spiske on Unsplash

Here is a simple cheat sheet when it comes to formatting outputs with the print function — print(), specifically numbers and data.

Rounding Decimals: (floating point numbers)

To round a number simply use the format() function to do so. The first argument will be the number you are wanting to format, and the second argument will be how you’d like to format it. Use f for floating point. The .2 is simply saying we are rounding 2 to the right of the decimal point.

use format() and ‘.2f’

You can pass in a comma (,) to also add a comma to your number format like so:

Format in Scientific Notation

If you need to format your output into a scientific notation format, use the format() function in conjunction with ‘e’.

Insert Comma Separator — Integer or Floating Point

Adding a comma is useful for handling large number especially in currency amounts. To use this with a floating point number simply pass ‘f’ for floating point as the number type. To use this with a integer or whole number, pass ‘d’ for digit as the number type.

Formatting a Percentage

To format a decimal (floating point) value as a percentage you simply pass the % character into the format() function as an argument.

For decimal placement simply pass a ‘.0’ or whichever number placement you’d like to see into the argument before the % char.

Suppress Print’s Newline

When using the print() function, python creates a new line each time you use it. To suppress this feature simple at the end= to the last argument of the print() function.

If you don’t put a space in between the ‘quotes’ , you won’t get a space.

Minimum Field Width

You can specify a minimum field with inside a format() function which will make a field x spaces wide; x being the number of spaces. This is useful for aligning columns to show decimal numbers.

--

--

<Blake†Codez />

I’m a Software Engineering student in Redding, Ca. Love all things Computer Science related, love for journalism, Jesus Christ, and team collaboration projects.