0

i want to round off a float to 3 dp in python with 00 in the end if the float don't have 3 dp like 15.4 into 15.400 thank you.

programme:

x=round(15.4)

result: 15.400

ledick
  • 13
  • 1

3 Answers3

2

The "rounding" you are talking about can only be done if you convert the float to a string. This is usually only done for display purposes. In this case you can use a so-called f-string to do this formatting:

x = 15.4
print(f"{x:.3f}")
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

Hello its pretty simple you can do something like this

a=15.4
b=("%.3f" % a)
print(b)
0

15.4 and 15.400 are the same number. round() returns a number. What you want is to have a different representation when you convert it to a string.

You need to do string formatting. Just copying the other answers here, there are two ways.

  • f-strings:
n = 15.4
n_str = f"{n:.3f}"
  • %-formatting:
n_str = "%.3f" % n
Martin Massera
  • 1,718
  • 1
  • 21
  • 47