Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

python - Fixed-point notation is not behaving acording to the documentation

I want to format some values with a fixed precision of 3 unless it's an integer. In that case I don't want any decimal point or trailing 0s.

Acording to the docs, the 'f' type in string formating should remove the decimal point if no digits follow it:

If no digits follow the decimal point, the decimal point is also removed unless the # option is used.

But testing it with python3.8 I get the following results:

>>> f'{123:.3f}'
'123.000'
>>> f'{123.0:.3f}'
'123.000'

Am I misunderstanding something? How could I achive the desired result without using if else checks?

question from:https://stackoverflow.com/questions/66060154/fixed-point-notation-is-not-behaving-acording-to-the-documentation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to forcefully achieve both your desired outputs with the same f-string expression, you could apply some kung-fu like

i = 123
f"{i:.{3*isinstance(i, float)}f}"
# '123'

i = 123.0
f"{i:.{3*isinstance(i, float)}f}"
# '123.000'

But this won't improve your code in terms of readability. There's no harm in being more explicit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...