Does python have an analog 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' Does python have an analog 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' Analogue of Number.prototype.toFixed() from JavaScript in 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' "{numObj:.{digits}f}".format(**vars()) - jfsThere is no direct analogue. You can also try
a = float('{:.3f}'.format(x)) Example:
>>> x = 3.1234567 >>> x = float('{:.3f}'.format(x)) >>> x 3.123 format(3.1234567, '.3f') - gil9redThis is how you can specify the number of decimal places in the output:
a = [1000, 2.4, 2.23456754323456, 2754.344] for i in a: print('%.3f' % i) # 3 знака после запятой Conclusion:
1000.000 2.400 2.235 2754.344 Here more.
def toFixed(f: float, n=0): a, b = str(f).split('.') return '{}.{}{}'.format(a, b[:n], '0'*(n-len(b))) f = 7.123 print(toFixed(f, 10)) # 7.1230000000 print(toFixed(f, 2)) # 7.12 Source: https://ru.stackoverflow.com/questions/648454/
All Articles