Python print double format

How to Format Float Values in Python

Here are 4 methods to format float in Python.

  1. Using the “format()” function
  2. Using the “%f” format specifier
  3. Using the “round()” function
  4. Using the “f-string” function

Method 1: Using the format() function

To format float values in Python, you can use the “format()” method. The format() method allows multiple substitutions and value formatting.

Example

x = 211911461911461819112146 y = 2**70 z = x / y print("".format(z))

The output returns a string. To get the output as float, use the float() function.

x = 211911461911461819112146 y = 2**70 z = x / y print(float("".format(z)))

Method 2: Using the “%f” format specifier

To format the float value up to two decimal places in Python, you can use the “%.2f” format specifier inside the “print()” function.

Example

x = 211911461911461819112146 y = 2**70 z = x / y print("%.2f" % z)

To format up to three decimal places, use the %.3f.

x = 211911461911461819112146 y = 2**70 z = x / y print("%.3f" % z)

You can see that when we are printing only two decimal places, it automatically rounds to the nearest integer.

Still, printing a number up to three decimal places does not go round to the nearest integer. The 0.496 prints as it is since we want a floating value up to three decimal places.

Читайте также:  Иконки для html верстки

How to Use the %d Formatter in Python

You can also use floating point numbers in Python with the “%d” formatter. This returns the whole number in a floating point number.

floatNumber = 2.9876 print("%d" % floatNumber) 

Method 3: Using the round() function

The “round()” is a built-in Python method that returns the floating-point number rounded off to the given digits after the decimal point.

Example

x = 211911461911461819112146 y = 2**70 z = x / y print(round(z, 2))

But please note that the behavior of the round() function for floats can be surprising in some cases. For example, round(3.575, 2) gives 3.57 instead of the expected 3.58.

This is not a bug: it’s a result that most decimal fractions can’t be represented exactly as a float.

Method 4: Using the Python f-strings

Python f-String is an improvement over previous formatting methods. You can read more at PEP8.

Let’s use the f-strings to format the float value.

Example

x = 211911461911461819112146 y = 2**70 z = x / y print(f'')

It works well with long calculations with operators and does not need parenthesis.

Conclusion

You can use the %f format specifier or string.format() function to format the float values in Python. You can also use the round() method or the f-string approach.

Источник

Форматирование чисел в 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!

При форматировании числа в процентах точность округления всегда относится к количеству цифр после точки.

Заключение

Вот и все! Мы разобрали самые ходовые способы вывода чисел в нужном формате. Теперь вы знаете, как ограничить количество цифр в выводимом числе, количество знаков в дробной части числа, как вывести число в удобном для чтения виде и в виде процентного значения.

1 комментарий к “Форматирование чисел в Python”

Источник

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:

Code block showing different ways to print an f-string using the string formatting mini-language covered in this blog post, and the expected outcome

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

Phil Best

I’m a freelance developer, mostly working in web development. I also create course content for Teclado!

Источник

Оцените статью