- Python number formatting examples
- Round float to 2 decimal places
- Format float as percentage
- Truncate float at 2 decimal places
- Left padding with zeros
- Right padding with zeros
- Use commas as thousands separator
- Interpolate variable with f-strings
- ValueError: zero length field name in format
- References
- Formatting Numbers for Printing in Python
- Format numbers rounded to certain decimal places
- Display separator character between thousands
- Format floating point numbers as percentages
- Wrapping Up
- Phil Best
- Форматирование чисел в Python
- Форматирование чисел с округлением
- Вывод числа с разбивкой на разряды
- Вывод числа в процентах
- Заключение
- 1 комментарий к “Форматирование чисел в Python”
Python number formatting examples
In other words, round it up to the nearest integer and format:
Round float to 2 decimal places
Format float as percentage
Format a number as a percentage, with 2 decimal places
Truncate float at 2 decimal places
View the full code for a generalized version on this notebook
Drop digits after the second decimal place (if there are any).
import re # see the notebook for a generalized version def truncate(num): return re.sub(r'^(\d+\.\d)\d*$',r'\1',str(num)) truncate(8.499) # >>> '8.49' truncate(8.49) # >>> '8.49' truncate(8.4) # >>> '8.4' truncate(8.0) # >>> '8.0' truncate(8) # >>> '8'
Left padding with zeros
Example make the full size equal to 9 (all included), filling with zeros to the left:
# make the total string size AT LEAST 9 (including digits and points), fill with zeros to the left '9>'.format(3.499) # >>> '00003.499'
# make the total string size AT LEAST 2 (all included), fill with zeros to the left '2>'.format(3) # >>> '03'
Right padding with zeros
Example make the full size equal to 11, filling with zeros to the right:
Use commas as thousands separator
Interpolate variable with f-strings
You can use any of the other formatting options with f-strings:
Example: truncate to 2 decimal places in f-string
num = 1.12745 formatted = f"" formatted # >>> '1.13'
ValueError: zero length field name in format
In some Python versions such as 2.6 and 3.0, you must specify positional indexes in the format string:
# ValueError in python 2.6 and 3.0 a=1 b=2 "<>-<>".format(a,b) # NO ERROR in any python version "-".format(a,b) # >>> "1-2"
References
Formatting Numbers for Printing in Python
Hey there, and welcome to another Python snippet post. Let’s take a look at how to print formatted numbers. We’ll cover rounding, thousands separators, and percentages.
Before we dive in, here’s a quick image overview:
String formatting is actually a surprisingly large topic, and Python has its own internal mini language just for handling the many formatting options available to us. Here we’re just going to focus on a few examples involving numbers, but there is a great deal more to explore.
Format numbers rounded to certain decimal places
First let’s take a look at formatting a floating point number to a given level of precision. There are two ways we can do this: we can specify how many significant figures we want overall, or we can specify how many significant figures we want after the decimal point. Let’s start with the former.
To specify a level of precision, we need to use a colon ( : ), followed by a decimal point, along with some integer representing the degree of precision. We place this inside the curly braces for an f-string, after the value we want to format. You can also use the format method instead, which I’ll demonstrate below.
x = 4863.4343091 # example float to format print(f"") # f-string version print("".format(x)) # format method version
In both cases we get the same result: 4863.43 .
As we can see, our very long float got shortened down to just 6 figures. An interesting thing to note is that this formatting operation actually performs rounding, so if x had a value of 4863.435 , the number printed would actually be 4863.44 . This uses bankers’ rounding (explained here).
If we specify fewer figures than we have in the integer portion of the float, we end up with an exponent representation instead:
x = 4863.4343091 print(f"") # 4.86e+03
4.86e+03 means 4.86 x 10³ , or 4.86 x 1000 , which is 4860 . Looking at this result, we see that we got three significant figures, as we requested.
So how do we specify 3 decimal places? We just need to add an f .
x = 4863.4343091 print(f"") # 4863.434
f indicates that we want our float displayed as a «fixed point number»: in other words, we want a specific number of digits after the decimal point. We can use f on its own as well, which defaults to 6 digits of precision:
x = 4863.4343091 print(f"") # 4863.434309
Display separator character between thousands
For large numbers we often write a separator character (usually a comma, space, or period) to make it easier to read. We can specify this in Python using a comma or underscore character after the colon.
x = 1000000 print(f"") # 1,000,000 print(f"") # 1_000_000
This also works with floats, and the precision formatting, with the comma coming first:
x = 4863.4343091 print(f"") # 4,863.434 print(f"") # 4_863.434
Format floating point numbers as percentages
We can format a number as a percentage by simply adding the percent symbol at the end of our formatting options instead of f :
questions = 30 correct_answers = 23 print(f"You got correct!") # You got 76.67% correct!
When formatting a number as a percentage, the level of precision always refers to the number of digits after the decimal point.
Wrapping Up
That’s it for our very brief dive into formatting numbers. There’s so much more to learn, and we’ll be tackling this in future posts, so make sure to follow us on Twitter to keep up to date with all our content.
We’re also offering our Complete Python Course at its lowest price just for readers of our blog. If you click the link, a coupon will already be applied for you. We’d love to have you, so if you’re looking to upgrade your Python skills, or if you’re just getting started, check it out!
Phil Best
I’m a freelance developer, mostly working in web development. I also create course content for Teclado!
Форматирование чисел в Python
Форматирование строк на самом деле является удивительно большой темой, и у Python есть собственный внутренний мини-язык для обработки множества доступных нам параметров форматирования. В этой статье мы разберем только форматирование чисел. Вы узнаете, как вывести число с нужным количеством знаков после запятой и с разбивкой по три цифры.
Форматирование чисел с округлением
Сначала давайте рассмотрим форматирование чисел с плавающей запятой до заданного уровня округления. Есть два способа сделать это: можно указать нужное количество значащих цифр в целом или количество значащих цифр после десятичной точки. Начнем с первого.
Чтобы указать уровень точности округления, нам нужно использовать двоеточие (:), за которым следует десятичная точка, а также некоторое целое число, представляющее степень точности (количество знаков после запятой). При использовании f-строки мы помещаем всё это после значения, которое хотим отформатировать (в фигурных скобках) . Вместо этого также можно использовать метод format.
x = 4863.4343091 # пример числа с плавающей запятой print(f"") # использование f-строки print("".format(x)) # использование метода format
В обоих случаях мы получаем одинаковый результат: 4863.43.
Как видите, наше довольно длинное число сократилось до шести цифр. Также следует отметить, что данная операция форматирования может производить еще и округление. Если, например, первоначальное число будет иметь значение 4863.435, то выведем в консоль мы 4863.44. Здесь используется округление до ближайшего четного числа (в английском языке banker’s rounding — «округление банкира»).
Если мы укажем меньше цифр, чем у нас есть в целочисленной части нашего числа с плавающей запятой, то получим экспоненциальное представление:
x = 4863.4343091 print(f"") # 4.86e+03
4.86e+03 означает 4,86 x 10³, или 4,86 x 1000, что равно 4860. Глядя на этот результат, мы видим, что получили три значащих цифры, как и хотели.
Итак, а как нам указать три десятичных знака после запятой? Для этого нужно просто добавить f .
x = 4863.4343091 print(f"") # 4863.434
f в данном случае указывает, что наше число типа float должно отображаться как «число с фиксированной точкой». То есть нам нужно определенное количество десятичных знаков. Мы также можем использовать f без числа, что по умолчанию означает точность 6 цифр после точки:
x = 4863.4343091 print(f"") # 4863.434309
Вывод числа с разбивкой на разряды
Большие числа зачастую удобно писать с использованием символов-разделителей (обычно это запятые, пробелы или точки). Это улучшает их восприятие при чтении. В Python мы можем указать, каким символом разбить цифры числа на классы, указав нужный символ после двоеточия:
x = 1000000 print(f"") # 1,000,000 print(f"") # 1_000_000
При форматировании чисел с плавающей запятой и форматировании с округлением это тоже работает:
x = 4863.4343091 print(f"") # 4,863.434 print(f"") # 4_863.434
Вывод числа в процентах
Мы можем вывести число в качестве процентного значения, просто добавив символ % в конце параметров форматирования вместо f :
questions = 30 correct_answers = 23 print(f"You got correct!") # You got 76.67% correct!
При форматировании числа в процентах точность округления всегда относится к количеству цифр после точки.
Заключение
Вот и все! Мы разобрали самые ходовые способы вывода чисел в нужном формате. Теперь вы знаете, как ограничить количество цифр в выводимом числе, количество знаков в дробной части числа, как вывести число в удобном для чтения виде и в виде процентного значения.