Explain Codes LogoExplain Codes Logo

Fixed digits after decimal with f-strings

python
f-strings
formatting
precision
Anton ShumikhinbyAnton Shumikhin·Aug 20, 2024
TLDR
# Trust me, I'm an Engineer! value = 7.12345 formatted = f"{value:.2f}" # '7.12' - Harry Potter and the Chamber of Digits

This magic spell :{width}.{precision}f within the braces lets you control decimals like a boss.

Precision and Width for Uniform Outputs

Create a perfectly uniform format:

# Wider than an elephant, and precise as a dart board! f"{value:10.2f}" # Results in ' 7.12', I'm on cloud 9... 10 actually!

The width gives your output a gym membership, keeping it fit and in shape.

Large Numbers? Say Hello to Thousands Separator

Enhance readability of large numbers:

# Who needs a calculator or abacus? 👀 f"{1234567.89:,.2f}" # '1,234,567.89', more punctuations than my English essay!

Great for financial statements or astronomical distances.

Alignment and Padding for Consistency

# Mirror, Mirror on the Wall, Who's the most Aligned of All? f"{value:<10.2f}" # '7.12 ', Because right-handers need some love too! f"{value:>10.2f}" # ' 7.12', Left is right!

Perfect when your table needs to look like it just got a military-style haircut.

Advanced Formatting Types with F-strings

Unleash the power of format specifiers for diverse outputs.

Need Percentages? Done!

# Because who needs a calculator anyway? rate = 0.12345 f"{rate:.2%}" # '12.35%', bet you didn't see that coming!

When Leading Zeros are "0h so important"!

# When your ID Card needs attention f"{23:05}" # '00023', zero calories, 100% formatted

Binary, Octal, or Hexadecimal - No Problem!

number = 255 f"{number:#x}" # '0xff', because hexadecimal is cooler! f"{number:#o}" # '0o377', bringing octal back! f"{number:#b}" # '0b11111111', more ones than a lottery winner!

Beware of Special Cases

Every rule has exceptions, just like f-strings.

When Rounding Throws You a Curveball

value = 2.675 f"{value:.2f}" # '2.67', wait... wasn't it supposed to be '2.68'?

Remember that one friend at school who always got weird scores?

Keeping it Consistent

# Because consistency brings balance in the force. value = 1.5 f"{value:06.2f}" # '001.50', beautifully balanced as all things should be.