If you have Python 2.6 or newer, use format:

'{0:.3g}'.format(num)

For Python 2.5 or older:

'%.3g'%(num)

Explanation:

{0}tells format to print the first argument -- in this case, num.

Everything after the colon (:) specifies the format_spec.

.3 sets the precision to 3.

g removes insignificant zeros. See http://en.wikipedia.org/wiki/Printf#fprintf

For example:

tests=[(1.00, '1'),
       (1.2, '1.2'),
       (1.23, '1.23'),
       (1.234, '1.23'),
       (1.2345, '1.23')]

for num, answer in tests:
    result = '{0:.3g}'.format(num)
    if result != answer:
        print('Error: {0} --> {1} != {2}'.format(num, result, answer))
        exit()
    else:
        print('{0} --> {1}'.format(num,result))

yields

1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23

Using Python 3.6 or newer, you could use f-strings:

In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'
Answer from unutbu on Stack Overflow
🌐
Python
docs.python.org › 3 › library › decimal.html
decimal — Decimal fixed-point and floating-point arithmetic
When clamp is 1, a large normal number will, where possible, have its exponent reduced and a corresponding number of zeros added to its coefficient, in order to fit the exponent constraints; this preserves the value of the number but loses information about significant trailing zeros. For example: >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999') Decimal('1.23000E+999') A clamp value of 1 allows compatibility with the fixed-width decimal interchange formats specified in IEEE 754.
Discussions

python - Limiting floats to two decimal points - Stack Overflow
Note that if you try to use this method to print out a number such as 1.00000 it will only print out 1.0, regardless of how many decimal points you specify. 2019-08-03T16:36:04.177Z+00:00 ... Let me give an example in Python 3.6's f-string/template-string format, which I think is beautifully neat: More on stackoverflow.com
🌐 stackoverflow.com
How to format to two decimal places python
There are several ways to do it, string formatting being one, but round is the easiest: String formatting: print('%.2f' % number) round: float_number = round(number, 2) More on reddit.com
🌐 r/learnprogramming
4
1
April 29, 2021
How do I represent currency (i.e., rounding to two decimal places) in Python? I just started learning a few days ago, and any explanation I've found of the decimal function is overwhelming at this point. ELI5, plz?

You're thinking about the wrong aspect of the problem. Yes, floating point innaccuracies mean you get a number like 30.00000000000000001, and decimal will fix that - but you can still divide a price and get a value like $3.718. Decimal won't help you there.

What you really want is a way to round the value to 2 decimal places when you print it. That's the only time that it matters, unless you're a bank and you really care about tiny fractions of a cent (in which case you'll use decimal as well as the following advice).

Check out the format function.

price=14.6188
print("The price is: ${:.2f}".format(price))
The price is: $14.62

This function is very powerful and you should get familiar with it.

product="beer"
print("The price of {:} is ${:.2f}".format(product, price))
The price of beer is $14.62
More on reddit.com
🌐 r/learnpython
19
12
November 16, 2013
Do you normally use string.format() or percentage (%) to format your Python strings?

Firstly, you can write e. g. {0:.2f} to specify a float with 2 decimals, see e. g. https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3

Secondly, the best formatting method is f-strings, see e. g. https://www.blog.pythonlibrary.org/2018/03/13/python-3-an-intro-to-f-strings/

More on reddit.com
🌐 r/Python
130
75
June 3, 2018
🌐
AskPython
askpython.com › home › how to format a number to 2 decimal places in python?
How to Format a Number to 2 Decimal Places in Python? - AskPython
February 27, 2023 - You can show the result using %f formatted, written inside quotation marks, and the % modulo operator separates it from the float number “%f” % num. Also, using str.format() is simple, where you have to write within the curly braces how many places you want after the decimal followed by the variable name in the format function. Here’s the official Python documentation to help you understand decimal in Python.
🌐
freeCodeCamp
freecodecamp.org › news › 2f-in-python-what-does-it-mean
%.2f in Python – What does it Mean?
June 22, 2022 - The %f formatter is specifically used for formatting float values (numbers with decimals). We can use the %f formatter to specify the number of decimal numbers to be returned when a fl...
🌐
Linux find Examples
queirozf.com › entries › python-number-formatting-examples
Python number formatting examples
August 2, 2023 - # ValueError in python 2.6 and 3.0 a=1 b=2 "{}-{}".format(a,b) # NO ERROR in any python version "{0}-{1}".format(a,b) # >>> "1-2"
🌐
GeeksforGeeks
geeksforgeeks.org › precision-handling-python
Precision Handling in Python - GeeksforGeeks
August 9, 2024 - Python provides for managing precise data and decimal points, the round() function is used to round a number to a specified number of decimal places. Alternatively, string formatting options, such as the f-string syntax or the format() method, ...
🌐
Python Guides
pythonguides.com › python-print-2-decimal-places
How to Print Two Decimal Places in Python
December 22, 2025 - They were introduced in Python 3.6 and have completely changed how I write code. They are fast, readable, and allow you to format numbers directly within the string. # Monthly subscription cost for a streaming service in the USA monthly_fee = 14.991234 # Using an f-string to format to 2 decimal places formatted_fee = f"Your monthly subscription is: ${monthly_fee:.2f}" print(formatted_fee) # Output: Your monthly subscription is: $14.99
Find elsewhere
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › functions › format.html
format — Python Reference (The Right Way) 0.1 documentation
Then if -4 <= exp < p, the number is formatted with presentation type ‘f’ and precision p-1-exp. Otherwise, the number is formatted with presentation type ‘e’ and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.
🌐
The Teclado Blog
blog.teclado.com › python-formatting-numbers-for-printing
Formatting Numbers for Printing in Python - The Teclado Blog
March 23, 2023 - 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.
🌐
Sololearn
sololearn.com › en › Discuss › 3288381 › how-to-round-to-2-decimal-places-in-python
How to round to 2 decimal places in python | Sololearn: Learn to code for FREE!
Yes, you can use the round() function in Python to round a float to a specific number of decimal places. In your case, you can use round(number, 2) to round the number to 2 decimal places.
🌐
mkaz.blog
mkaz.blog › working-with-python › string-formatting
Python String Formatting: Complete Guide
F-strings support comprehensive number formatting using format specifications after a colon: value = 1234.5678 # Basic decimal places print(f"Two decimals: {value:.2f}") # 1234.57 print(f"No decimals: {value:.0f}") # 1235 print(f"With sign: {value:+.2f}") # +1234.57 # Padding and alignment print(f"Right aligned: {value:10.2f}") # 1234.57 print(f"Left aligned: {value:<10.2f}") # 1234.57 print(f"Center aligned: {value:^10.2f}") # 1234.57 print(f"Zero padded: {value:010.2f}") # 001234.57 # Thousands separator print(f"With commas: {value:,.2f}") # 1,234.57 # Percentage ratio = 0.857 print(f"Percentage: {ratio:.1%}") # 85.7% # Scientific notation big_number = 1500000 print(f"Scientific: {big_number:.2e}") # 1.50e+06 # Different bases num = 255 print(f"Hex: {num:x}") # ff print(f"Binary: {num:b}") # 11111111 print(f"Octal: {num:o}") # 377
🌐
mkaz.blog
mkaz.blog › code › python-string-format-cookbook
String Formatting - mkaz.blog
July 15, 2021 - F-strings support comprehensive number formatting using format specifications after a colon: value = 1234.5678 # Basic decimal places print(f"Two decimals: {value:.2f}") # 1234.57 print(f"No decimals: {value:.0f}") # 1235 print(f"With sign: {value:+.2f}") # +1234.57 # Padding and alignment print(f"Right aligned: {value:10.2f}") # 1234.57 print(f"Left aligned: {value:<10.2f}") # 1234.57 print(f"Center aligned: {value:^10.2f}") # 1234.57 print(f"Zero padded: {value:010.2f}") # 001234.57 # Thousands separator print(f"With commas: {value:,.2f}") # 1,234.57 # Percentage ratio = 0.857 print(f"Percentage: {ratio:.1%}") # 85.7% # Scientific notation big_number = 1500000 print(f"Scientific: {big_number:.2e}") # 1.50e+06 # Different bases num = 255 print(f"Hex: {num:x}") # ff print(f"Binary: {num:b}") # 11111111 print(f"Octal: {num:o}") # 377
Top answer
1 of 16
2331

You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.

With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).

Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.

For example,

>>> 125650429603636838/(2**53)
13.949999999999999

>>> 234042163/(2**24)
13.949999988079071

>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999

If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:

  1. Use integers and store values in cents, not dollars and then divide by 100 to convert to dollars.
  2. Or use a fixed point number like decimal.
2 of 16
838

There are new format specifications, String Format Specification Mini-Language:

You can do the same as:

"{:.2f}".format(13.949999999999999)

Note 1: the above returns a string. In order to get as float, simply wrap with float(...):

float("{:.2f}".format(13.949999999999999))

Note 2: wrapping with float() doesn't change anything:

>>> x = 13.949999999999999999
>>> x
13.95
>>> g = float("{:.2f}".format(x))
>>> g
13.95
>>> x == g
True
>>> h = round(x, 2)
>>> h
13.95
>>> x == h
True
🌐
LabEx
labex.io › tutorials › python-how-to-format-decimal-output-in-python-421895
How to format decimal output in Python | LabEx
Learn essential techniques for formatting decimal numbers in Python, including precision control, rounding, and display methods for professional data presentation.
🌐
Quora
quora.com › How-do-you-print-decimals-in-Python
How to print decimals in Python - Quora
Answer (1 of 4): I’ll be generous and pretend you’re not a Troll. Python has a wonderful function called print(). You can put whatever you want in the parentheses, or even nothing (that prints a blank line). Suppose x = 3.14159 Then print(x) produces 3.14159 decimals and all.
🌐
Real Python
realpython.com › how-to-python-f-string-format-float
How to Format Floats Within F-Strings in Python – Real Python
April 24, 2024 - To use Python’s format specifiers in a replacement field, you separate them from the expression with a colon (:). As you can see, your float has been rounded to two decimal places. You achieved this by adding the format specifier .2f into the replacement field. The 2 is the precision, while the lowercase f is an example of a presentation type. You’ll see more of these later. Note: When you use a format specifier, you don’t actually change the underlying number. You only improve its display. Python’s f-strings also have their own mini-language that allows you to format your output in a variety of different ways.
🌐
Analytics Vidhya
analyticsvidhya.com › home › 6 ways to round floating value to two decimals in python
6 Ways to Round Floating Value to Two Decimals in Python
November 4, 2024 - By applying the .2f format specifier within the format() method and using the "{:.2f}" format string, the number is formatted to have two decimal places. The resulting formatted_number is then printed, which outputs 3.14 ...
🌐
PyFormat
pyformat.info
PyFormat: Using % and .format() for great good!
In the example below we want our output to have at least 6 characters with 2 after the decimal point. ... For integer values providing a precision doesn't make much sense and is actually forbidden in the new style (it will result in a ValueError). ... By default only negative numbers are prefixed with a sign. This can be changed of course. ... Use a space character to indicate that negative numbers should be prefixed with a minus symbol and a leading space should be used for positive ones. ... New style formatting is also able to control the position of the sign symbol relative to the padding.
🌐
Codecademy
codecademy.com › article › rounding-to-two-decimal-places-in-pythonn
Rounding to Two Decimal Places in Python | Codecademy
Let’s look at an example of how we can use str.format() to round a number to two decimal places: ... Let’s look at another approach for string formatting. In Python, the % operator, also called modulus operator, We can use this operator ...
🌐
Pocoo
babel.pocoo.org › en › latest › numbers.html
Number Formatting — Babel 2.17.0 documentation
By default, Python rounding mode is ROUND_HALF_EVEN which complies with UTS #35 section 3.3. Yet, the caller has the opportunity to tweak the current context before formatting a number or currency: >>> from babel.numbers import decimal, format_decimal >>> with decimal.localcontext(decimal.Context(rounding=decimal.ROUND_DOWN)): >>> txt = format_decimal(123.99, format='#', locale='en_US') >>> txt '123'