Fixed number of decimal places in Python

Question:

Does python have a counterpart to the toFixed() function in JS? I need something like this:

>>> a = 12.3456789
>>> a.toFixed(2)
'12.35'
>>> a.toFixed(0)
'12'
>>> b = 12.000001
>>> b.toFixed(3)
'12.000'

Answer:

Аналог Number.prototype.toFixed() из JavaScript в Python 3.6+:

def toFixed(numObj, digits=0):
    return f"{numObj:.{digits}f}"

Example:

>>> numObj = 12345.6789
>>> toFixed(numObj)
'12346'
>>> toFixed(numObj, 1)
'12345.7'
>>> toFixed(numObj, 6)
'12345.678900'
>>> toFixed(1.23e+20, 2)
'123000000000000000000.00'
>>> toFixed(1.23e-10, 2)
'0.00'
>>> toFixed(2.34, 1)
'2.3'
>>> toFixed(2.35, 1)
'2.4'
>>> toFixed(-2.34, 1)
'-2.3'
Scroll to Top