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' 
  • Various options have already been written to you in the answers. I decided to add more about precision . - Mr. Brightside

4 answers 4

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' 
  • And what is the literal f? And how were the variables in the string picked up? Saw similar in JS, but there is a special type of string - gil9red
  • @ gil9red PEP 498 - jfs
  • Ofiget, thank you :) Useful to read docs.python.org/3/whatsnew/3.6.html :) - gil9red
  • 3.6 cool, but it doesn't support old 2k3 platforms - vadim vaduxa
  • @vadimvaduxa: on older versions: "{numObj:.{digits}f}".format(**vars()) - jfs

There 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 
  • 3
    You can still do this: format(3.1234567, '.3f') - gil9red
  • @ gil9red live and learn)) ATP, did not know. - andy.37

This 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.

  • and how is the print ('%. 3f'% i) record better (worse) than the record x = float ('{:. 3f}'. format (x))? - Rashid_s 1:56 pm
  • one
    @ Rashid-s, it is recommended to use format in Python 3. stackoverflow.com/questions/12382719/… - Cyril Malyshev
 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