-1

In Python 3.11

I want to print out the following number: 10.235689 like this: 10.23 I don't want to introduce a new variable I don't want to change the original value of 10.235689 to 10.23 I don't want the number to be rounded to 10.24 I want to specify how many digits to be printed after the decimal point.

Thank you in advance.

Stackoverflow and google

me my
  • 1

1 Answers1

0

What you're asking for is truncation. As far as i'm aware of you cannot do it with string formatting but only using some manual operations like below.

n = 10.235689
print(int(n*100)/100) # 10.23

As @user2390182 mentions this might give some erronous results due to floating point accuracy. In that case, it might be better to round the number to one more digit and then print all but the last digit as follows:

n = 10.235689
print(str(round(n,3))[:-1]) # 10.23
Thomas Wagenaar
  • 6,489
  • 5
  • 30
  • 73
  • This is risky as the result is a float which has accuracy problems to begin with. You still might get something like `10.230000000001` in some cases. – user2390182 Jun 07 '23 at 08:48