Skip to content

Python decimal format

  • by

Use the format() function to get decimal format in Python. {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.

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

Python decimal format example

Simple example topic.

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

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

Output:

Python decimal format

How to display two decimal points in python, when a number is perfectly divisible?

Answer: The division works and returns adequate precision in results. You can use string formatting for that. For example in Python 3, use f-strings:

The trick does .2f, a string formatting literal or format specifier that represents a floating-point number (f) with two fractional digits after the decimal point (.2).

twoFractionDigits = f"{result:.2f}"

or

twoFractionDigits = f"{result:.2f}"

Example code

import math

a = 1.175
result = math.floor(a * 100) / 100
print(f"{result:.2f}")

Do comment if you have any doubts or suggestions on this Python decimal topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *