Home python Python fixed decimal places

Python fixed decimal places

Author

Date

Category

Does python have an analogue of the toFixed () function in JS? I need something like this:

& gt; & gt; & gt; a = 12.3456789
& gt; & gt; & gt; a.toFixed (2)
'12 .35 '
& gt; & gt; & gt; a.toFixed (0)
'12'
& gt; & gt; & gt; b = 12.000001
& gt; & gt; & gt; b.toFixed (3)
'12 .000 '

Answer 1, authority 100%

Analogue Number.prototype. toFixed () from JavaScript in Python 3.6+:

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

Example:

& gt; & gt; & gt; numObj = 12345.6789
& gt; & gt; & gt; toFixed (numObj)
'12346'
& gt; & gt; & gt; toFixed (numObj, 1)
'12345.7'
& gt; & gt; & gt; toFixed (numObj, 6)
'12345.678900'
& gt; & gt; & gt; toFixed (1.23e + 20, 2)
'123000000000000000000.00'
& gt; & gt; & gt; toFixed (1.23e-10, 2)
'0.00'
& gt; & gt; & gt; toFixed (2.34, 1)
'2.3'
& gt; & gt; & gt; toFixed (2.35, 1)
'2.4'
& gt; & gt; & gt; toFixed (-2.34, 1)
'-2.3'

Answer 2, authority 57%

There is no direct analogue. You can try

a = float ('{:. 3f}'. format (x))

Example:

& gt; & gt; & gt; x = 3.1234567
& gt; & gt; & gt; x = float ('{:. 3f}'. format (x))
& gt; & gt; & gt; x
3.123

Answer 3, authority 29%

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 decimal places

Output:

1000.000
2.400
2.235
2754.344

Read more here .


Answer 4, authority 7%

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

Answer 5, authority 7%

It seems to me that you are complicating things a little. There is a wonderful round () function, into which you can pass a number, and, separated by commas, pass the number of characters after. Since there will still be rounding there

d = round (3.14, 1)
print (d) # 3.1

Answer 6

I am using the built-in module for this. It is clear that it returns Decimal, but I then convert it back to float.

from decimal import Decimal
number = Decimal ('0.424242')
number = number.quantize (Decimal ('1.000'))
number = float (number)
# returns true because both data types are now float
print (0.424 == number)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions