0

I know that I can to the following. But is it possible to combine them to give me a percent with fixed decimal?

>>> print(f'{0.123:%}')
12.300000%
>>> print(f'{0.123:.2f}')
0.12

But what I want is this output:

12.30%
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
tturbo
  • 680
  • 5
  • 16
  • 4
    `f'{0.123:.2%}'` – Samwise Nov 24 '22 at 07:52
  • 1
    Does this answer your question? [How to display two decimal points in python, when a number is perfectly divisible?](https://stackoverflow.com/questions/70882733/how-to-display-two-decimal-points-in-python-when-a-number-is-perfectly-divisibl) – Jeanot Zubler Nov 24 '22 at 07:56
  • @JeanotZubler Although it contains the answer, the title of the question is not obviously the same. I searched on stackoverflow for an answer before asking, but found nothing. I hope the clear title will help others with the same question. – tturbo Nov 24 '22 at 08:06
  • The google search `python format percentage 2 decimal places` returns 2 blogs and quite a few StackOverflow posts where this is solved. Looking for f strings specifically gives slightly worse results, but still solvable from the first page of google. – Jeanot Zubler Nov 24 '22 at 08:14

1 Answers1

3

You can specify the number of decimal places before %:

>>> f'{0.123:.2%}' 
'12.30%'
Lord Elrond
  • 13,430
  • 7
  • 40
  • 80
  • Omg, I have tried so many compositions but not this. Thanks for that! It makes total sense... – tturbo Nov 24 '22 at 08:03